﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using TwainDotNet;
using TwainDotNet.TwainNative;
using TwainDotNet.Win32;
using TwainDotNet.Wpf;
using TestTreeView.Model;
using Microsoft.Win32;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using BarcodeReader = ZXing.Presentation.BarcodeReader;
using TestTreeView;
using System.Web.Script.Serialization;
using MSSClient.Model;
using System.ComponentModel;
using System.Runtime.Serialization.Json;
using ZXing;
using System.Diagnostics;
using MSSClient.Utils;
using Spire.Barcode;
using TestDragDropTreeView;
using System.Windows.Controls;
using System.Threading;
using System.Collections.ObjectModel;
using OpenCvSharp;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using Zmy.Wpf.CMessageBox;
using MSSClient.OCR;

namespace MSSClient
{
    
    /// <summary>
    /// Interaction logic for MSSWindow.xaml
    /// </summary>
    public partial class MSSWindow : System.Windows.Window
    {
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        private const int WS_SHOWNORMAL = 1;
        FileSystemWatcher watcher = new FileSystemWatcher(); //文件监控-新建，修改，删除等

        #region 变量
        private ObservableCollection<SucceseListModel> nowListData = new ObservableCollection<SucceseListModel>(); //当前上传数据
        private ObservableCollection<SucceseListModel> succeseListDate = new ObservableCollection<SucceseListModel>(); //上传成功数据
        private ObservableCollection<SucceseListModel> failListDate = new ObservableCollection<SucceseListModel>(); //上传失败数据
        private static AreaSettings AreaSettings = new AreaSettings(Units.Centimeters, 0.1f, 5.7f, 0.1F + 2.6f, 5.7f + 2.6f);
        private Twain _twain; //扫描工具类
        private ScanSettings _settings; //扫描设置
        private IList<TreeModel> m_treeList = new List<TreeModel>();
        private IList<TreeModel> _treeToDelList = new List<TreeModel>();
        private IList<GroupModel> _groupToDelList = new List<GroupModel>();
        private readonly BarcodeReader m_reader = new BarcodeReader();
        private Boolean m_bBarcode = false;
        private String m_strBarcode = "";//条形码
        public String remenberTheuserName;
        private Boolean m_bDetectBarcode;
        private Boolean m_bDetectWhitePaper;
        private Boolean m_bDetectBarcodeSetting;
        private Boolean m_bDetectWhitePaperSetting;
        public Boolean isDrag = false;
        private Boolean tisaoScanning;  //替扫标识
        private Boolean busaoScanning;  //补扫标识
        public ConfigData m_configData;
        private int saveStatus = 1;
        private int scanpageCountSuessce = 0;
        private int scanpageCountFail = 0;
        private int upLoadModel = 1;//1-被动模式,2主动模式
        private int upLoadTypeTag = 1;//1-ftp上传，2-应用上传
        private long qualityValue = 50L;
        private Boolean IsDebug = false;//OCR调试模式 true-开启，false-关闭
        public LoginData loginData;
        public TreeModel ScanTypeTemp;//用于扫描时的中间变量
        public String ImagePathGlobal;//用于扫描时的中间变量
        String OCRTrigger = "false";//是否启用ocr过滤发票
        String OSVersionName = ""; //获取系统类型
        private bool InsertTag = false;
        private int InsertPointCount = 0;
        ScaleTransform st;
        TranslateTransform tt;
        TransformGroup group;
        System.Windows.Point startPoint;
        ListModel listModle = new ListModel();
        List<System.Drawing.Image> ScanImageList = new List<System.Drawing.Image>();//用来收集扫描进来的图像
        List<ImageOcrModel> imageOcrModelList = new List<ImageOcrModel>(); //用来收集结果ocr处理的图像数据
        #endregion

        public MSSWindow()
        {
            #region 初始化方法
            InitializeComponent();

            this.DataContext = listModle;
            upLoadList.DataContext = nowListData;
            upLoadList.ItemsSource = nowListData;
            succeseListView.DataContext = succeseListDate;
            succeseListView.ItemsSource = succeseListDate;
            FailListView.DataContext = failListDate;
            FailListView.ItemsSource = failListDate;

            //初始化界面尺寸
            PrimaryScreen ps = new PrimaryScreen();
            double x = (ps.DpiX + 4) * 0.01;
            double y = (ps.DpiY + 4) * 0.01;

            System.Drawing.Rectangle rect = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
            double h = rect.Height * 0.9 / y; //高（像素）
            double w = rect.Width * 0.9 / x; //宽（像素）

            invoiceBtn.Visibility = Visibility.Collapsed;
            info.Visibility = Visibility.Collapsed;

            this.Height = h;
            this.Width = w;

            m_bDetectBarcodeSetting = true;
            m_bDetectWhitePaperSetting = true;

            tisaoScanning = false;
            busaoScanning = false;

            tvc.MainWindow = this;
            tvc.ImageData = MainImage;//绑定图像属性

            OSVersionName = CommonUtil.GetOsVersion(Environment.OSVersion.Version);

            #region 控件ZsmTreeView绑定委托事件
            tvc.delItemDelegateObj += (TreeModel delItem) =>
            {
                deleteImage(delItem);//删除节点
            };

            tvc.addFolderDelegate += () =>
            {
                addFolderByZsmTreeView();//添加文件夹
            };

            tvc.deleteDelegate += () =>
            {
                deleteTree();//删除选择的节点下的所有数据
            };

            tvc.moveImageDelegate += (TreeModel selectNode, Stuff selectGroup) =>
            {
                moveImage(selectNode, selectGroup);//转移图像
            };

            tvc.breakUpImageDelegate += (String groupName) =>
            {
                breakUpImageDelegate(groupName);//拆分分组
            };

            tvc.showGridDelegate += () =>
            {
                showGrid();//显示图像预览
            };
            #endregion

            Loaded += Window_Loaded;//绑定程序加载时触发的事件

            Closing += MSSWindow_Closed;//绑定程序关闭时间
             
            #endregion
        }

        /// <summary>
        /// 关闭窗口时回调事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MSSWindow_Closed(object sender, CancelEventArgs e)
        {
            #region 窗口关闭
            CMessageBoxResult cmr = CMessageBox.Show("是否退出程序？窗口关闭后，数据即将丢失！是否现在关闭窗口", "退出提示", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
            if (cmr.Equals(CMessageBoxResult.OK))
            {
                string fileName = (string)userNameCN.Content + "_nowUploadResultData.bin";
                string filePath = "C:/MssClientCache/";//缓存保存地址
                if (File.Exists(filePath + fileName))
                {
                    File.Delete(filePath + fileName);
                }
                CommonUtil.clearCache(false, 0);//退出程序清楚缓存
                SaveConfig();
                Process.GetCurrentProcess().Kill();
            }
            e.Cancel = true;
            return;
            #endregion
        }

        private void Window_Loaded(object s, RoutedEventArgs e)
        {
            #region 窗口加载
            group = (TransformGroup)grd.RenderTransform;
            st = group.Children[0] as ScaleTransform;
            tt = group.Children[3] as TranslateTransform;
            remenberTheuserName = (string)userNameCN.Content;

            TvcDataBind();//数据绑定
            if (null != Global.getInstance().getOCRTrigger)
                OCRTrigger = Global.getInstance().getOCRTrigger.value;
            //创建文件夹
            string filePath = @"C:\MssClientCache\imageCache\";//缓存保存地址
            string imagePath = @"C:\MssClientCache\Scannned\";//图像缓存保存地址
            string QrCachePath = @"C:\MssClientCache\QrCache";
            if (!Directory.Exists(filePath))//判断文件夹是否存在 
            {
                Directory.CreateDirectory(filePath);//不存在则创建文件夹 
            }
            if (!Directory.Exists(imagePath))
            {
                Directory.CreateDirectory(imagePath);
            }
            if (!Directory.Exists(QrCachePath))
            { 
                Directory.CreateDirectory(QrCachePath);
            }
            try
            {
                //监控缓存文件变化
                watcher.Path = "C:/MssClientCache/";
                watcher.Filter = "*.txt";
                watcher.Created += new FileSystemEventHandler(UpgradeFileCreate);
                watcher.EnableRaisingEvents = true;

                //绑定扫描委托事件
                _twain = new Twain(new WpfWindowMessageHook(this));
                _twain.TransferImage += delegate (Object sender, TransferImageEventArgs args)
                {
                    if (args.Image != null)
                    {
                        AddImageToTreeList(args.Image, "", "scan", DateTime.Now.ToString("yyyyMMddHHmmssfff"), ScanTypeTemp);
                        if (!OSVersionName.Equals("WinXP"))
                        {
                            MainImage.Source = new BitmapImage(new Uri(ImagePathGlobal));
                            ImagePathGlobal = "";
                        }
                        if (InsertTag)
                        {
                            InsertPointCount++;
                        }
                        //搜集图像
                        //String dateSec = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        //String imageUrl = @"C:\MssClientCache\Scannned\" + dateSec + ".jpg";
                        //CommonUtil.SaveScanImgae(args.Image, imageUrl, qualityValue);
                        //ImageOcrModel imageOcrModel = new ImageOcrModel();
                        //imageOcrModel.imageUrl = imageUrl;
                        //imageOcrModel.Count = countScan;
                        //imageOcrModelList.Add(imageOcrModel);
                        //ScanImageList.Add(args.Image);
                    }
                    CommonUtil.ClearMemory();
                };
                //扫描完成回调事件，重置tisaoScanning，busaoScanning等状态
                _twain.ScanningComplete += delegate
                {
                    #region
                    //多线程处理图像
                    //CommonUtil.ShowMsgFrom("正在后台处理图像，请稍等...");
                    //ThreadPool.SetMaxThreads(4, 4);
                    //foreach (ImageOcrModel o in imageOcrModelList)
                    //{
                    //    ImageOcrModel Temp = new ImageOcrModel();

                    //    //ThreadPool.QueueUserWorkItem(state => ImageOcrProcesses(ScanImageList,o,counttt), null);
                    //    ThreadPool.QueueUserWorkItem(h =>
                    //    {
                    //        Thread.Sleep(50);
                    //        Temp = ImageOcrProcessesByLocal(o, false);
                    //        int index = imageOcrModelList.IndexOf(Temp);//定位合并的节点在数组中位置
                    //        Console.WriteLine("index:" + index);
                    //        //imageOcrModelList[counttt-1].isIdentifying = Temp.isIdentifying;//替换图像的路径
                    //    });
                    //    //imageOcrModelList.Contains(Temp);
                    //}
                    //imageOcrModelList.Clear();
                    #endregion

                    IsEnabled = true;
                    m_bDetectBarcode = m_bDetectBarcodeSetting;
                    m_bDetectWhitePaper = m_bDetectWhitePaperSetting;
                    m_bBarcode = false;

                    tisaoScanning = false;
                    busaoScanning = false;
                    CommonUtil.ClearMemory();
                    CommonUtil.ShowMsgFrom("扫描结束，共扫描：" + scanpageCountSuessce + "页。其中成功加载[" + (scanpageCountSuessce - scanpageCountFail) + "]张，失败：[" + scanpageCountFail + "]张。");
                    scanpageCountSuessce = 0;//重置数量
                    scanpageCountFail = 0;
                };

                if (File.Exists("C://MssClientCache//BudanInfoGet.txt"))
                {
                    BudanInfoGet(false);
                    File.Delete("C://MssClientCache//BudanInfoGet.txt");
                }
            }
            catch (TwainException ex)
            {
                CommonUtil.WriteLog(ex);
                CommonUtil.ShowMsgFrom("温馨提示：没有找到扫描设备！！");
                //MessageBox.Show("温馨提示：没有找到扫描设备！！");
            }
            //补单任务获取
            //budanInfoCheck();
            #endregion
        }

        System.Windows.Forms.Timer aTimer = new System.Windows.Forms.Timer();
        //System.Timers.Timer aTimer = new System.Timers.Timer();
        //补单任务信息查询
        private void budanInfoCheck()
        {
            //aTimer.Elapsed += OnTimedEvent;//触发的时间 OnTimedEvent
            aTimer.Tick += new EventHandler(OnTimedEvent);
            aTimer.Interval = 12000;//12000毫秒/12秒触发一次，检查是否有补单任务
            aTimer.Enabled = true;
            GC.KeepAlive(aTimer);
        }


        //自动获取补单任务逻辑-暂不启用 
        private void OnTimedEvent(object O, EventArgs e)
        {
            
        }

        /// <summary>
        /// 数据绑定
        /// </summary>
        private void TvcDataBind()
        {
            LoadConfig();
            tvc.ItemsSourceData = m_treeList;
        }

        /// <summary>
        /// 扫描按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saomiao_Click(object sender, RoutedEventArgs e)
        {
            #region 扫描
            try
            {
                ScanTypeTemp = ZsmTreeView.s_selectedTreeModel;
                //没有选择节点，默认报账单节点
                if (null == ScanTypeTemp)
                {
                    ZsmTreeView.s_selectedTreeModel = m_treeList[0];
                    ScanTypeTemp = ZsmTreeView.s_selectedTreeModel;
                }

                //如果选到具体一个图像，自动获取对应的分组
                if (3 == ScanTypeTemp.level)
                {
                    ZsmTreeView.s_selectedTreeModel = ScanTypeTemp.Parent;
                }

                lastGroupName = "";//未重命名组名重置
                m_strBarcode = "";//条形码重置
                tempBarCode = "";//条形码重置
                busaoTag = 0;//重置补扫标识
                IsEnabled = false;

                //evaResult为1和5说明只需要删除,不能补扫图像和添加图像
                //if (null != ZsmTreeView.s_selectedTreeModel && 1.Equals(ZsmTreeView.s_selectedTreeModel.isBiSaoType)
                //    && (1.Equals(ZsmTreeView.s_selectedTreeModel.evaResult) || 3.Equals(ZsmTreeView.s_selectedTreeModel.evaResult) || 5.Equals(ZsmTreeView.s_selectedTreeModel.evaResult)))
                //{
                //    CMessageBox.Show("该补单单据不需要添加图像，请直接提交！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                //    IsEnabled = true;
                //    return;
                //}

                if (ZsmTreeView.s_selectedTreeModel.level.Equals(2) && ZsmTreeView.s_selectedTreeModel.isBiSaoType.Equals(1))
                {
                    CMessageBox.Show("不能选择补单单据！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                    IsEnabled = true;
                    return;
                }

                //evaResult为1和3说明只需要删除,不能补扫图像和添加图像
                //if (null != ZsmTreeView.s_selectedTreeModel && 1.Equals(ZsmTreeView.s_selectedTreeModel.isBiSaoType))
                //{
                //    busaoScanning = true;
                //}

                _settings = new ScanSettings
                {
                    PageSettings = new PageSettings
                    {
                        Size = PageType.A4, //纸张大小
                        Orientation = TwainDotNet.TwainNative.Orientation.Default //旋转角度
                    },
                    UseDocumentFeeder = false,
                    ShowTwainUI = true,//是否显示扫描设置的UI界面
                    ShowProgressIndicatorUI = false,
                    UseDuplex = false,
                    Resolution = ResolutionSettings.Fax,
                    ShouldTransferAllPages = true,
                    UseAutoScanCache = true,//是否等待程序返回，才扫描下一张，指示源是否应该继续扫描，而无需等待应用程序请求图像传输。 false-等待，true-不等待
                    Rotation = new RotationSettings
                    {
                        AutomaticRotate = false,
                        AutomaticBorderDetection = false
                    }
                };

                if (null == _twain)
                {
                    IsEnabled = true;
                    CommonUtil.ShowMsgFrom("请插入扫描仪。");
                    //MessageBox.Show("请插入扫描仪。");
                    return;
                }
                if (m_configData.SourceListPos < 0)
                {
                    IsEnabled = true;
                    CMessageBox.Show("请在设置中选择一个扫描仪", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                    return;
                }
                IsEnabled = true;
                _twain.SelectSource(_twain.SourceNames[m_configData.SourceListPos]);
                _twain.StartScanning(_settings);
            }
            catch (TwainException ex)
            {
                IsEnabled = true;
                MessageBox.Show(ex.Message);
                return;
            }
            IsEnabled = true;
            #endregion
        }

        //替扫按钮
        private void tisao_Click(object sender, RoutedEventArgs e)
        {
            #region 替扫
            ScanTypeTemp = ZsmTreeView.s_selectedTreeModel;
            lastGroupName = "";//未重命名组名重置
            m_strBarcode = "";//条形码重置
            tempBarCode = "";//条形码重置     
            IList<TreeModel> treeList = tvc.CheckedLevel2Items();

            if (null == ZsmTreeView.s_selectedTreeModel)
            {
                CMessageBox.Show("您还没有选择具体要重扫替换的图像", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }
            //当选择了一级树结构
            if (1 == ZsmTreeView.s_selectedTreeModel.level)
            {
                CMessageBox.Show("请选择具体要重扫替换的图像。", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }
            //当选择了二级树结构
            if (2 == ZsmTreeView.s_selectedTreeModel.level)
            {
                CMessageBox.Show("请选择具体要重扫替换的图像", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }
            //选择的组是补单的
            if (null != ZsmTreeView.s_selectedTreeModel && ZsmTreeView.s_selectedTreeModel.Parent.isBiSaoType.Equals(1))
            {
                CMessageBox.Show("补单任务不能点击替扫", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }

            IsEnabled = false;

            _settings = new ScanSettings
            {
                PageSettings = new PageSettings
                {
                    Size = PageType.A4, //纸张大小
                    Orientation = TwainDotNet.TwainNative.Orientation.Default //旋转角度
                },
                UseDocumentFeeder = true,
                ShowTwainUI = true,//是否显示扫描设置的UI界面
                ShowProgressIndicatorUI = true,
                UseDuplex = false,
                Resolution = ResolutionSettings.Fax,
                ShouldTransferAllPages = true,
                UseAutoScanCache = true,//是否等待程序返回，才扫描下一张，指示源是否应该继续扫描，而无需等待应用程序请求图像传输。 false-等待，true-不等待
                Rotation = new RotationSettings
                {
                    AutomaticRotate = false,
                    AutomaticBorderDetection = false
                }
            };

            try
            {
                if (null == _twain)
                {
                    CommonUtil.ShowMsgFrom("请插入扫描仪。");
                    //MessageBox.Show("请插入扫描仪。");
                    IsEnabled = true;
                    return;
                }
                _twain.SelectSource(_twain.SourceNames[m_configData.SourceListPos]);
                _twain.StartScanning(_settings);
            }
            catch (TwainException ex)
            {
                MessageBox.Show(ex.Message);

                m_bDetectBarcode = m_bDetectBarcodeSetting;
                m_bDetectWhitePaper = m_bDetectWhitePaperSetting;
                tisaoScanning = false;// 替扫标识
                IsEnabled = true;
                return;
            }

            IsEnabled = true;

            m_bDetectBarcode = false;
            m_bDetectWhitePaper = false;
            tisaoScanning = true;//替扫标识
            #endregion
        }

        //补扫按钮
        private void busao_Click(object sender, RoutedEventArgs e)
        {
            #region 补扫
            InsertPointCount = 0;
            lastGroupName = "";//未重命名组名重置
            m_strBarcode = "";//条形码重置
            tempBarCode = "";//条形码重置
            busaoTag = 0;//重置补扫
            ScanTypeTemp = ZsmTreeView.s_selectedTreeModel;
            if (null == ZsmTreeView.s_selectedTreeModel)
            {
                CMessageBox.Show("现在还没有选择分组。", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }

            if (1 == ZsmTreeView.s_selectedTreeModel.level)
            {
                CMessageBox.Show("现在选择的不是一个分组或具体的图像。", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }

            if ((2 == ZsmTreeView.s_selectedTreeModel.level || 3 == ZsmTreeView.s_selectedTreeModel.level) && !ZsmTreeView.s_selectedTreeModel.isBiSaoType.Equals(1))
            {
                CMessageBox.Show("现在选择的分组不是补单分组！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }

            if(3 == ZsmTreeView.s_selectedTreeModel.level)
            {
                ZsmTreeView.s_selectedTreeModel.Parent.InsertPoint = (ZsmTreeView.s_selectedTreeModel.count).ToString();
                InsertTag = true;
                InsertPointCount = ZsmTreeView.s_selectedTreeModel.count;
                Console.WriteLine("busao-InsertPointCount:"+ InsertPointCount);            }

            if (ZsmTreeView.s_selectedTreeModel.isBiSaoType.Equals(1))
            {
                if (ZsmTreeView.s_selectedTreeModel.evaResult.Equals(3) || ZsmTreeView.s_selectedTreeModel.evaResult.Equals(1) || ZsmTreeView.s_selectedTreeModel.evaResult.Equals(5))
                {
                    CMessageBox.Show("该补单单据不需要添加图像，请直接提交。", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                    return;
                }
            }

            _settings = new ScanSettings
            {
                PageSettings = new PageSettings
                {
                    Size = PageType.A4, //纸张大小
                    Orientation = TwainDotNet.TwainNative.Orientation.Default //旋转角度
                },
                UseDocumentFeeder = true,
                ShowTwainUI = true,//是否显示扫描设置的UI界面
                ShowProgressIndicatorUI = true,
                UseDuplex = false,
                Resolution = ResolutionSettings.Fax,
                ShouldTransferAllPages = true,
                UseAutoScanCache = true,//是否等待程序返回，才扫描下一张，指示源是否应该继续扫描，而无需等待应用程序请求图像传输。 false-等待，true-不等待
                Rotation = new RotationSettings
                {
                    AutomaticRotate = false,
                    AutomaticBorderDetection = false
                }
            };

            try
            {
                if (null == _twain)
                {
                    CommonUtil.ShowMsgFrom("请插入扫描仪。");
                    IsEnabled = true;
                    return;
                }
                if (null != m_configData)
                {
                    _twain.SelectSource(_twain.SourceNames[m_configData.SourceListPos]);
                    _twain.StartScanning(_settings);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                CommonUtil.WriteLog(ex);
                m_bDetectBarcode = m_bDetectBarcodeSetting;
                m_bDetectWhitePaper = m_bDetectWhitePaperSetting;
                busaoScanning = false;
                IsEnabled = true;
                return;
            }

            IsEnabled = true;

            m_bDetectBarcode = false;
            m_bDetectWhitePaper = false;
            busaoScanning = true;
            #endregion
        }

        #region
        //private void testWinScp()
        //{
        //    try
        //    {
        //        SessionOptions sessionOptions = new SessionOptions
        //        {
        //            Protocol = Protocol.Ftp,
        //            HostName = "192.168.167.124",
        //            UserName = "image2016",
        //            Password = "image2016",
        //            FtpMode = FtpMode.Passive,
        //            PortNumber = 21
        //        };
        //        Session session = new Session();
        //        session.Open(sessionOptions);

        //        String[] fileList = { "E:\\1.jpg", "E:\\2.jpg", "E:\\3.jpg" };
        //        //CommonUtil.testWinScp(session, fileList,"");
        //    }
        //    catch (WinSCP.SessionRemoteException ex)
        //    {
        //        //Authentication failed 用户/密码错误
        //        //Connection failed. 连接失败：1.超时，2.网络不通
        //        MessageBox.Show(ex.Message);
        //        CommonUtil.WriteLog(ex);
        //    }
        //}
        #endregion

        int isIdentifyingCount = 0;
        int isOcrSuccessCount = 0;
        //打开上传
        private void dakai_Click(object sender, RoutedEventArgs e)
        {
            InsertPointCount = 0;
            //CommonUtil.printDemo();
            #region
            TreeModel tree = ZsmTreeView.s_selectedTreeModel;
            busaoTag = 0;//重置Tag为0
            isIdentifyingCount = 0;

            //没有选择节点，默认报账单节点
            if (null == tree)
            {
                ZsmTreeView.s_selectedTreeModel = m_treeList[0];
                tree = ZsmTreeView.s_selectedTreeModel;
            }

            if (null != ZsmTreeView.s_selectedTreeModel && 1.Equals(ZsmTreeView.s_selectedTreeModel.isBiSaoType)
               && (!1.Equals(ZsmTreeView.s_selectedTreeModel.evaResult) || !5.Equals(ZsmTreeView.s_selectedTreeModel.evaResult)))
            {
                busaoTag = 1;
                //补单选择具体一张，获取具体的选择点
                if (3 == tree.level)
                {
                    tree.Parent.InsertPoint = (tree.count).ToString();
                    InsertPointCount =Int16.Parse(tree.Parent.InsertPoint) -1;
                    Console.WriteLine("dakai-InsertPointCount:" + InsertPointCount);
                    InsertTag = true;
                }
            }

            //evaResult为1和3说明只需要删除,不能补扫图像和添加图像
            if (null != tree && 1.Equals(tree.isBiSaoType)
                && (3.Equals(tree.evaResult) || 1.Equals(tree.evaResult) || 5.Equals(tree.evaResult)))
            {
                CMessageBox.Show("该补单单据不需要添加图像，请直接提交。", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }

            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "图片文件(*.jpg,*.png)|*.jpg;*.png;*.jpeg";//规定指定的格式
            dialog.Multiselect = true;//是否可以多选
            lastGroupName = "";//未重命名组名重置
            m_strBarcode = "";//条形码重置
            tempBarCode = "";//条形码重置
            m_bBarcode = false;//是否执行条形码分组逻辑重置
            BackgroundWorker worker = new BackgroundWorker();

            //busyIndicator.IsBusy = true;
            //busyIndicator.BusyContent = "正在导入图像中，请稍等...";
            TreeModel SelectTreeModel = ZsmTreeView.s_selectedTreeModel;
            string dic = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            if (dialog.ShowDialog() == true)
            {
                int count1 = 1;
                worker.DoWork += (o, a) =>
                {
                    foreach (String fileName in dialog.FileNames)
                    {
                        if (InsertTag)
                        {
                            InsertPointCount++;
                        }
                        //BitmapImage bitmapImage = new BitmapImage(new Uri(fileName));//转换成bitmapImage提供给控件显示图片
                        //this.MainImage.Dispatcher.Invoke(new Action(delegate
                        //{
                        //    MainImage.Source = bitmapImage;//strImagePath 就绝对路径
                        //}));
                        using (Bitmap bitImage = new Bitmap(fileName))
                            AddImageToTreeList(bitImage, fileName, "up", dic, SelectTreeModel);
                        count1++;
                    }
                };
                worker.RunWorkerCompleted += (o, a) =>
                {
                    CommonUtil.ShowMsgFrom("成功导入：" + SucceeImportCount + "张，其中识别发票数量：" + isIdentifyingCount + ",识别出发票信息数量：" + isOcrSuccessCount);
                    isOcrSuccessCount = 0;
                    SucceeImportCount = 0;
                };
                worker.RunWorkerAsync();
            }
            //else
                //busyIndicator.IsBusy = false;
            #endregion
        }

        /// <summary>
        /// 
        /// </summary>
        private void NewOpenFiles(object sender, RoutedEventArgs e)
        {
            #region
            try
            {
                TreeModel tree = ZsmTreeView.s_selectedTreeModel;
                busaoTag = 0;//重置Tag为0
                testCount = 1;//序号重置为1
                isIdentifyingCount = 0;
                imageOcrModelList.Clear();//重置imageOcrList
                                          //没有选择节点，默认报账单节点
                if (null == tree)
                {
                    ZsmTreeView.s_selectedTreeModel = m_treeList[0];
                    tree = ZsmTreeView.s_selectedTreeModel;
                }

                if (null != ZsmTreeView.s_selectedTreeModel && 1.Equals(ZsmTreeView.s_selectedTreeModel.isBiSaoType)
                   && (!1.Equals(ZsmTreeView.s_selectedTreeModel.evaResult) || !5.Equals(ZsmTreeView.s_selectedTreeModel.evaResult)))
                    busaoTag = 1;

                //如果选到具体一个图像，自动获取对应的分组
                if (3 == tree.level)
                    ZsmTreeView.s_selectedTreeModel = tree.Parent;

                //evaResult为1和3说明只需要删除,不能补扫图像和添加图像
                if (null != tree && 1.Equals(tree.isBiSaoType)
                    && (3.Equals(tree.evaResult) || 1.Equals(tree.evaResult) || 5.Equals(tree.evaResult)))
                {
                    MessageBox.Show("该补单单据不需要添加图像，请直接提交！", "提示信息");
                    return;
                }

                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Filter = "图片文件(*.jpg,*.png)|*.jpg;*.png;*.jpeg";//规定指定的格式
                dialog.Multiselect = true;//是否可以多选
                lastGroupName = "";//未重命名组名重置
                m_strBarcode = "";//条形码重置
                tempBarCode = "";//条形码重置
                m_bBarcode = false;//是否执行条形码分组逻辑重置

                string dic = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                if (dialog.ShowDialog() == true)
                {
                    int imageOcrModelCount = 1;
                    
                    foreach (String fileName in dialog.FileNames)
                    {
                        ImageOcrModel imageOcrModel = new ImageOcrModel();
                        imageOcrModel.imageUrl = fileName;//获取所选图像的路径
                        imageOcrModel.Count = imageOcrModelCount;
                        imageOcrModelList.Add(imageOcrModel);
                        imageOcrModelCount++;
                    }
                    CommonUtil.ShowMsgFrom("正在后台处理图像，请稍等...");
                    ThreadPool.SetMaxThreads(4, 4);
                    foreach (ImageOcrModel o in imageOcrModelList)
                    {
                        ImageOcrModel Temp = new ImageOcrModel();

                        //ThreadPool.QueueUserWorkItem(state => ImageOcrProcesses(ScanImageList,o,counttt), null);
                        ThreadPool.QueueUserWorkItem(h =>
                        {
                            Thread.Sleep(50);
                            Temp = ImageOcrProcessesByLocal(o,false);
                            int index = imageOcrModelList.IndexOf(Temp);//定位合并的节点在数组中位置
                            Console.WriteLine("index:" + index);
                            //imageOcrModelList[counttt-1].isIdentifying = Temp.isIdentifying;//替换图像的路径
                        });
                        //imageOcrModelList.Contains(Temp);
                    }
                    ImageOcrModel Temp5 = new ImageOcrModel();
                    Temp5 = imageOcrModelList[0];
                    isOcrSuccessCount = 0;
                    SucceeImportCount = 0;
                }
            }
            catch(Exception ex)
            {
                return;
            }
            #endregion
        }

        int testCount = 1;
        /// <summary>
        /// ocr识别处理-多线程:本地上传
        /// 
        /// </summary>
        /// <param name="ScanImageDic">扫描收集的图像</param>
        /// <param name="imageOcrModelDic">本地上传的图像</param>
        /// <returns></returns>
        private ImageOcrModel ImageOcrProcessesByLocal(ImageOcrModel o,Boolean TypeTag)
        {
            #region
            InvoiceModel invoiceModelTemp = new InvoiceModel();
            try
            {
                bool checkQrCodeTag = true;//是否需要识别二维码标识
                Mat mat = new Mat();
                String dateSec = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                String imageUrl = @"C:\MssClientCache\Scannned\" + dateSec + o.Count + ".jpg";
                //Console.WriteLine("多线程地址:" + o.imageUrl);
                if (TypeTag)
                {
                    CommonUtil.SaveScanImgae(o.image, imageUrl, qualityValue);
                }
                else
                {
                    using (Bitmap bitImage = new Bitmap(o.imageUrl))
                        CommonUtil.SaveScanImgae(bitImage, imageUrl, qualityValue);
                }
                
                o.imageUrl = imageUrl;
                mat = Cv2.ImRead(o.imageUrl);
                string Type = "";
                Type = ZsmTreeView.s_selectedTreeModel.Id;
                if (Type == "1")
                    checkQrCodeTag = QRDecodeUtil.DetectInvoiceHeadImage(mat, o.imageUrl, "tetse", IsDebug); //识别图像是否含有发票抬头

                List<String> qrCodeInfo = QRDecodeUtil.DetectImageQrCode(mat, o.imageUrl, "tetse", IsDebug);

                if (qrCodeInfo.Count == 1 && qrCodeInfo[0].Equals("Check"))
                    checkQrCodeTag = true;
                else if (qrCodeInfo.Count == 2)
                {
                    checkQrCodeTag = true;
                    String[] info = qrCodeInfo[1].Split(',');
                    if (info.Length == 9 || info.Length == 8 || info.Length == 7 || info.Length == 6)
                    {
                        invoiceModelTemp = InvoiceModel.LoadModelInfo(qrCodeInfo[1]);
                        if ("" != invoiceModelTemp.invoiceNum && "" != invoiceModelTemp.invoiceCode)
                        {
                            //isOcrSuccessCount++;
                        }
                    }
                }
                if (checkQrCodeTag) ;
                    //isIdentifyingCount++;

                OcrAfterInfoLoad(invoiceModelTemp,o);
            }
            catch (Exception ex)
            {
                OcrAfterInfoLoad(invoiceModelTemp,o);
                CommonUtil.WriteLog(ex);
                CommonUtil.ClearMemory();
            }
            CommonUtil.ClearMemory();
            return o;
            #endregion
        }

        static Object locker = new Object();
        private void OcrAfterInfoLoad(InvoiceModel invoiceModelTemp, ImageOcrModel o)
        {
            Console.WriteLine(locker.ToString());
            lock (locker)
            {
                TreeModel parentTree = ZsmTreeView.s_selectedTreeModel;
                TreeModel grandChild = new TreeModel();
                if ("" != invoiceModelTemp.invoiceNum)
                    grandChild.Name = "testname_" + testCount + "_发票";
                else
                    grandChild.Name = "testname_" + testCount;

                grandChild.count = parentTree.Children.Count + 1;
                grandChild.invoiceModel = invoiceModelTemp;
                grandChild.IsExpanded = true;
                grandChild.IsChecked = true;
                grandChild.ImageUrl = o.imageUrl;
                grandChild.Parent = parentTree;
                grandChild.Barcode = "";
                grandChild.IsIdentifying = 1;
                grandChild.level = 3;
                parentTree.IsExpanded = true;
                tvc.Dispatcher.Invoke(new Action(() =>
                {
                    parentTree.Children.Add(grandChild);
                }));

                testCount++;
            }
        }

        private int busaoTag = 0; //是否是通过打开本地来上传图像到分组，0-不是，1-是
        private string lastGroupName = "";//记录一次上传中的分组组名
        private string tempBarCode = "";//针对报账单和发票的过滤识别，记录上一个条形码
        private int SucceeImportCount = 0;//记录导入成功的图像

        /// <summary>
        /// 加载图像到目录下
        /// </summary>
        /// <param name="bitmap">图像bitmap数据</param>
        /// <param name="filePath">图像的路径</param>
        /// <param name="type">调用类型，scan-扫描，up-打开本地</param>
        private void AddImageToTreeList(Bitmap bitmap, string filePath, string type ,string dic,TreeModel SelectTreeModel)
        {
            #region
            try
            {
                String dateSec = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                String imageUrl = @"C:\MssClientCache\Scannned\" + dateSec + ".jpg";
                ImagePathGlobal = imageUrl;
                InvoiceModel invoiceModelTemp = new InvoiceModel();
                bool checkBarCodeTag = true;//是否需要识别条形码标识
                bool checkQrCodeTag = false;//是否需要识别二维码标识
                int  isOCRSuccess = 2;//是否识别出发票信息 2-否，1-是
                SucceeImportCount++;
                scanpageCountSuessce++;
                CommonUtil.SaveScanImgae(bitmap, imageUrl, qualityValue);
                filePath = imageUrl;

                if (m_bDetectBarcode)
                {
                    TimeSpan ts1 = new TimeSpan(DateTime.Now.Ticks); //获取当前时间的刻度数
                    #region 识别条码OBR
                    String[] spireBarCode = { };
                    if (loginData.data.provinceCode == "09" && (
                        (SelectTreeModel.level.Equals(1) && SelectTreeModel.Id == "1") 
                        || (SelectTreeModel.level.Equals(2) && SelectTreeModel.Type == "1")))
                    {
                        spireBarCode = BarcodeScanner.Scan(bitmap, BarCodeType.Code39);
                        if (spireBarCode.Length != 0)
                        {
                            m_strBarcode = spireBarCode[0];
                            m_bBarcode = true;
                            checkBarCodeTag = false;
                        }
                        TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
                        TimeSpan ts = ts2.Subtract(ts1).Duration(); //时间差的绝对值
                        string spanTotalSeconds = ts.TotalSeconds.ToString(); //执行时间的总秒数
                        Console.WriteLine("识别条码1耗时："+spanTotalSeconds);
                        //string spanTime = ts.Hours.ToString() + "小时" + ts.Minutes.ToString() + "分" + ts.Seconds.ToString() + "秒"; //以X小时X分X秒的格式现实执行时间
                    }
                    else
                    {
                        //spireBarcode识别
                        spireBarCode = BarcodeScanner.Scan(bitmap, BarCodeType.Code39);
                        if (spireBarCode.Length == 0)
                            spireBarCode = BarcodeScanner.Scan(bitmap, BarCodeType.Code128);
                        if (spireBarCode.Length != 0)
                        {
                            m_strBarcode = spireBarCode[0];
                            m_bBarcode = true;
                            checkBarCodeTag = false;

                        }
                        TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
                        TimeSpan ts = ts2.Subtract(ts1).Duration(); //时间差的绝对值
                        string spanTotalSeconds = ts.TotalSeconds.ToString(); //执行时间的总秒数
                        Console.WriteLine("识别条码2耗时：" + spanTotalSeconds);
                    }
                    #endregion

                    #region 报账单类型作过滤：只过滤报账单与发票类型
                    if (m_strBarcode != "")
                    {
                        if (SelectTreeModel.level.Equals(1) && !SelectTreeModel.Id.Equals("3") )
                        {
                            if (CommonUtil.bizTypeCheck(m_strBarcode, SelectTreeModel.Id))
                            {
                                tempBarCode = m_strBarcode;
                                m_bBarcode = true;
                            }
                            else
                            {
                                m_strBarcode = tempBarCode;
                                m_bBarcode = true;
                            }
                        }
                        m_bBarcode = true;
                    }
                    #endregion

                    #region 根据系统来启用opencv处理,xp系统不做识别，广东地区不识别
                    if (checkBarCodeTag && (OSVersionName != "" && OSVersionName != "WinXP") && loginData.data.provinceCode!="09")
                    {
                        Mat mat = Cv2.ImRead(filePath);
                        //string Type = "";
                        //Type = SelectTreeModel.Id;
                        //if (SelectTreeModel.level == 2)
                        //    Type = SelectTreeModel.Parent.Id;
                        //if (SelectTreeModel.level == 3)
                        //    Type = SelectTreeModel.Parent.Parent.Id;
                        //if (Type == "1")
                        //    checkQrCodeTag = QRDecodeUtil.DetectInvoiceHeadImage(mat, filePath, dic, IsDebug); //识别图像是否含有发票抬头

                        List<String> qrCodeInfo = QRDecodeUtil.DetectImageQrCode(mat,filePath, dic, IsDebug);

                         if (qrCodeInfo.Count == 1 && qrCodeInfo[0].Equals("Check"))
                            checkQrCodeTag = true;
                        else if (qrCodeInfo.Count == 2)
                        {
                            checkQrCodeTag = true;
                            String[] info = qrCodeInfo[1].Split(',');
                            if (info.Length == 9 || info.Length == 8 || info.Length == 7 || info.Length == 6)
                            {
                                invoiceModelTemp = InvoiceModel.LoadModelInfo(qrCodeInfo[1]);
                                if ("" != invoiceModelTemp.invoiceNum && "" != invoiceModelTemp.invoiceCode)
                                {
                                    isOcrSuccessCount++;
                                    isOCRSuccess = 1;
                                }
                            }
                        }
                        if (checkQrCodeTag)
                            isIdentifyingCount++;
                    }
                    //if (checkBarCodeTag && (OSVersionName == "" || OSVersionName == "WinXP"))
                    //    MessageBox.Show("当前系统为：XP，已跳过二维码识别...");
                    #endregion
                }
                else m_bBarcode = false;

                bitmap.Dispose();

                #region 替扫逻辑
                if (tisaoScanning)
                {
                    //把原来的图片URL替换
                    tvc.Dispatcher.Invoke(new Action(() =>
                    {
                        SelectTreeModel.ImageUrl = imageUrl;
                    }));
                    
                    //MainImage.Source = bitmapImage;
                    CommonUtil.ClearMemory();
                    return;
                }
                #endregion

                #region 补扫逻辑-扫描仪
                if (busaoScanning)
                {
                    TreeModel parentTree = SelectTreeModel;
                    TreeModel grandChild = new TreeModel();
                    grandChild.nameTag.Add("[补]");
                    grandChild.count = parentTree.Children.Count + 1;
                    //补单任务通过扫描仪补扫
                    if (parentTree.isBiSaoType.Equals(1))
                         grandChild.Name = parentTree.repImageCode + "-" + grandChild.count + CommonUtil.getTreeModelNameTag(grandChild.nameTag);
                    else
                    {
                        if (parentTree.isFail.Equals(1))
                            grandChild.Name = parentTree.imageCode + "-" + grandChild.count + CommonUtil.getTreeModelNameTag(grandChild.nameTag);
                        else grandChild.Name = parentTree.Name + "-" + grandChild.count + CommonUtil.getTreeModelNameTag(grandChild.nameTag);
                    }
                    //grandChild.nameTag.Add("[" + OcrUtil.DecodeInvoiceTypeByCn(invoiceModelTemp.invoiceType) +"]");
                    //grandChild.Name = parentTree.repImageCode + "-" + grandChild.count + CommonUtil.getTreeModelNameTag(grandChild.nameTag);
                    grandChild.IsIdentifying = 1;
                    //if (isOCRSuccess.Equals(1))
                    //{
                    //    grandChild.IsOCRSuccess = 1;
                    //    grandChild.IsClientOcr = 1;
                    //}
                    //else 
                    //    grandChild.IsOCRSuccess = 2;

                    grandChild.Id = dateSec ;
                    grandChild.imageCode = parentTree.imageCode;
                    grandChild.repImageCode = parentTree.repImageCode;
                    grandChild.Date = dateSec;
                    grandChild.IsExpanded = true;
                    grandChild.IsChecked = false;
                    grandChild.ImageUrl = imageUrl;
                    grandChild.level = 3;
                    grandChild.InvoiceModelFun = invoiceModelTemp;
                    grandChild.Parent = parentTree;
                    grandChild.Type = parentTree.Type;
                    grandChild.Barcode = "";
                    //补单任务通过扫描仪补扫
                    if (parentTree.isBiSaoType.Equals(1))
                    {
                        grandChild.isBuSaoTag = 1;
                        grandChild.isDelete = 2;//通过上传进去的可以删除
                    }
                    tvc.Dispatcher.Invoke(new Action(() =>
                    {
                        if (parentTree.level.Equals(2))
                        {
                            parentTree.Children.Add(grandChild);
                        }
                        if (parentTree.level.Equals(3))
                        {
                            parentTree.Parent.InsertTag = true;
                            grandChild.Parent = parentTree.Parent;
                            grandChild.InsertTag = true;
                            parentTree.Parent.Children.Insert(InsertPointCount, grandChild);
                            CommonUtil.SortTreeModelCount(parentTree.Parent);
                        }
                    }));
                    CommonUtil.ClearMemory();
                    return;
                }
                #endregion

                #region 补单-打开本地补扫逻辑
                if (busaoTag.Equals(1))
                {
                    TreeModel parentTree = SelectTreeModel;
                    TreeModel grandChild = new TreeModel();
                    grandChild.nameTag.Add("[补]");
                    grandChild.count = parentTree.Children.Count + 1;
                    grandChild.Id = dateSec;
                    grandChild.bizId = SelectTreeModel.bizId;
                    if (parentTree.isBiSaoType.Equals(1))
                        grandChild.Name = parentTree.repImageCode + "_" + grandChild.count + CommonUtil.getTreeModelNameTag(grandChild.nameTag);
                    //grandChild.nameTag.Add("[" + OcrUtil.DecodeInvoiceTypeByCn(invoiceModelTemp.invoiceType) + "]");
                    //grandChild.Name = parentTree.repImageCode + "_" + grandChild.count + CommonUtil.getTreeModelNameTag(grandChild.nameTag);
                    grandChild.IsIdentifying = 1;
                    //if (isOCRSuccess.Equals(1))
                    //{
                    //    grandChild.IsOCRSuccess = 1;
                    //    grandChild.IsClientOcr = 1;
                    //}
                    //else
                    //    grandChild.IsOCRSuccess = 2;

                    grandChild.Date = dateSec;
                    grandChild.IsExpanded = true;
                    grandChild.IsChecked = true;
                    grandChild.imageCode = parentTree.imageCode;
                    grandChild.repImageCode = parentTree.repImageCode;
                    grandChild.ImageUrl = imageUrl;
                    grandChild.Parent = parentTree;
                    grandChild.Barcode = "";
                    grandChild.level = 3;
                    grandChild.Type = parentTree.Type;
                    grandChild.isBuSaoTag = 1;
                    grandChild.isBiSaoType = 1;
                    grandChild.isDelete = 2;//通过上传进去的可以删除
                    grandChild.InvoiceModelFun = invoiceModelTemp;
                    parentTree.IsExpanded = true;
                    tvc.Dispatcher.Invoke(new Action(() =>
                    {
                        if (parentTree.level.Equals(2))
                        {
                            parentTree.Children.Add(grandChild);
                        }
                        if (parentTree.level.Equals(3))
                        {
                            grandChild.InsertTag = true;
                            parentTree.Parent.InsertTag = true;
                            grandChild.Parent = parentTree.Parent;
                            parentTree.Parent.Children.Insert(InsertPointCount, grandChild);
                            CommonUtil.SortTreeModelCount(parentTree.Parent);
                        }
                    }));
                    CommonUtil.ClearMemory();
                    return;
                }
                #endregion

                #region 正常扫描-选择某个类型下具体某个组
                if (1 != SelectTreeModel.level)
                {
                    TreeModel parentTree = SelectTreeModel;

                    TreeModel grandChild = new TreeModel();
                    grandChild.Id = dateSec;
                    grandChild.bizId = dateSec;
                    grandChild.count = parentTree.Children.Count + 1;
                    if (parentTree.isFail.Equals(1))
                        grandChild.Name = parentTree.imageCode + "_" + grandChild.count;
                    else
                        grandChild.Name = parentTree.Name + "_" + grandChild.count;
                    if (checkQrCodeTag)
                    {
                        grandChild.nameTag.Add("[" + OcrUtil.DecodeInvoiceTypeByCn(invoiceModelTemp.invoiceType) + "]");
                        grandChild.Name = parentTree.Name + "_" + grandChild.count + CommonUtil.getTreeModelNameTag(grandChild.nameTag);
                        grandChild.IsIdentifying = 1;
                    }
                    if (isOCRSuccess.Equals(1))
                    { 
                        grandChild.IsOCRSuccess = 1;
                        grandChild.IsClientOcr = 1;
                    }
                    else
                        grandChild.IsOCRSuccess = 2;

                    grandChild.Date = dateSec;
                    grandChild.IsExpanded = true;
                    grandChild.IsChecked = true;
                    grandChild.ImageUrl = imageUrl;
                    grandChild.Parent = parentTree;
                    grandChild.Type = parentTree.Type;
                    grandChild.Barcode = "";
                    grandChild.level = 3;
                    parentTree.IsExpanded = true;
                    grandChild.InvoiceModelFun = invoiceModelTemp;
                    tvc.Dispatcher.Invoke(new Action(() =>
                    {
                        if (parentTree.level.Equals(2))
                        {
                            parentTree.Children.Add(grandChild);
                        }
                        if (parentTree.level.Equals(3))
                        {
                            parentTree.Parent.InsertTag = true;
                            parentTree.Parent.Children.Insert(parentTree.Parent.Children.IndexOf(SelectTreeModel) + 1, grandChild);
                            CommonUtil.SortTreeModelCount(parentTree.Parent);
                        }
                    }));
                    CommonUtil.ClearMemory();
                    return;
                }
                #endregion

                #region 正常扫描-选择类型，新建分组

                //识别有条形码的处理逻辑
                if (m_bBarcode && m_strBarcode != "")
                {
                    TreeModel selectLv1Tree = SelectTreeModel;
                    TreeModel childToAdd = new TreeModel();
                    Boolean createNewGroupTag = true;//是否需要新建分组，true-需要，false-不需要

                    foreach (TreeModel child in selectLv1Tree.Children)
                    {
                        //判断是否已存在这个条码
                        if (child.Name.Equals(m_strBarcode) && m_strBarcode != "")
                        {
                            childToAdd = child;
                            createNewGroupTag = false;
                        }
                        else{}
                    }

                    //新建分组-如果 所选类型 下的所有分组 没有对应条码的分组
                    if (createNewGroupTag)
                    {
                        TreeModel newChild = new TreeModel();
                        newChild.Id = dateSec;
                        newChild.bizId = dateSec;
                        newChild.Name = m_strBarcode;
                        newChild.imageCode = m_strBarcode;
                        newChild.IsExpanded = true;
                        newChild.IsChecked = true;
                        newChild.level = 2;
                        newChild.Type = selectLv1Tree.Type;
                        newChild.Parent = selectLv1Tree;
                        tvc.Dispatcher.Invoke(new Action(() =>
                        {
                            selectLv1Tree.Children.Add(newChild);
                        }));
                        childToAdd = newChild;
                    }

                    TreeModel grandChild = new TreeModel();
                    grandChild.count = childToAdd.Children.Count + 1;
                    grandChild.Id = dateSec;
                    grandChild.bizId = dateSec;
                    grandChild.Name = m_strBarcode + "_" + (childToAdd.Children.Count + 1);
                    if (checkQrCodeTag)
                    {
                        grandChild.nameTag.Add("[" + OcrUtil.DecodeInvoiceTypeByCn(invoiceModelTemp.invoiceType) + "]");
                        grandChild.Name = m_strBarcode + "_" + grandChild.count + CommonUtil.getTreeModelNameTag(grandChild.nameTag);
                        grandChild.IsIdentifying = 1;
                    }
                    if (isOCRSuccess.Equals(1))
                    {
                        grandChild.IsOCRSuccess = 1;
                        grandChild.IsClientOcr = 1;
                    }
                    else
                        grandChild.IsOCRSuccess = 2;

                    grandChild.Date = dateSec;
                    grandChild.IsExpanded = true;
                    grandChild.IsChecked = true;
                    grandChild.level = 3;
                    grandChild.Type = selectLv1Tree.Type;
                    grandChild.ImageUrl = imageUrl;
                    grandChild.Parent = childToAdd;
                    grandChild.Barcode = m_strBarcode;
                    grandChild.InvoiceModelFun = invoiceModelTemp;
                    tvc.Dispatcher.Invoke(new Action(() =>
                    {
                        childToAdd.Children.Add(grandChild);
                    }));
                    //childToAdd.Children.Add(grandChild);

                    //ZsmTreeView.s_selectedTreeModel = grandChild;
                    //ZsmTreeView.s_selectedTreeModel.IsSelected = true;
                }

                //识别没有条形码处理逻辑
                else
                {
                    bool isSameGroupTag = true;//是否同一个分组
                    TreeModel selectLv1Tree = SelectTreeModel;
                    foreach (TreeModel child in selectLv1Tree.Children)
                    {
                        //同一分组
                        if (child.Name.Equals(lastGroupName) && lastGroupName != "")
                        {
                            isSameGroupTag = false;
                            TreeModel grandChild = new TreeModel();
                            grandChild.count = child.Children.Count + 1;
                            grandChild.Id = dateSec;
                            grandChild.bizId = dateSec;
                            grandChild.imageCode = lastGroupName;
                            grandChild.Type = selectLv1Tree.Type;
                            grandChild.level = 3;
                            grandChild.Name = lastGroupName + "_" + grandChild.count;
                            if (checkQrCodeTag)
                            {
                                grandChild.nameTag.Add("[" + OcrUtil.DecodeInvoiceTypeByCn(invoiceModelTemp.invoiceType) + "]");
                                grandChild.IsIdentifying = 1;
                                grandChild.Name = lastGroupName + "_" + grandChild.count + CommonUtil.getTreeModelNameTag(grandChild.nameTag);
                            }
                            if (isOCRSuccess.Equals(1))
                            {
                                grandChild.IsOCRSuccess = 1;
                                grandChild.IsClientOcr = 1;
                            }
                            else
                                grandChild.IsOCRSuccess = 2;

                            grandChild.Date = dateSec;
                            grandChild.IsExpanded = true;
                            grandChild.IsChecked = true;
                            grandChild.ImageUrl = imageUrl;
                            grandChild.Parent = child;
                            grandChild.Barcode = "";
                            grandChild.InvoiceModelFun = invoiceModelTemp;

                            child.IsExpanded = true;
                            tvc.Dispatcher.Invoke(new Action(() =>
                            {
                                child.Children.Add(grandChild);
                            }));
                            //child.Children.Add(grandChild);

                            //ZsmTreeView.s_selectedTreeModel = grandChild;
                            //ZsmTreeView.s_selectedTreeModel.IsSelected = true;
                        }
                    }
                    //新建一个组
                    if (isSameGroupTag)
                    {
                        TreeModel newChild = new TreeModel();
                        
                        newChild.Id = dateSec;
                        newChild.bizId = dateSec;
                        lastGroupName = "未重命名_" + DateTime.Now.ToString("sfff");
                        newChild.Name = lastGroupName;
                        newChild.imageCode = lastGroupName;
                        newChild.IsExpanded = true;
                        newChild.IsChecked = false;
                        newChild.Parent = selectLv1Tree;
                        newChild.level = 2;
                        newChild.Type = SelectTreeModel.Type;
                        tvc.Dispatcher.Invoke(new Action(() =>
                        {
                            selectLv1Tree.Children.Add(newChild);
                        }));
                        //selectLv1Tree.Children.Add(newChild);

                        TreeModel grandChild = new TreeModel();
                        grandChild.count = newChild.Children.Count + 1;
                        grandChild.Id = dateSec;
                        grandChild.bizId = dateSec;
                        grandChild.Type = newChild.Type;
                        grandChild.Name = lastGroupName + "_" + grandChild.count;
                        if (checkQrCodeTag)
                        {
                            grandChild.nameTag.Add("[" + OcrUtil.DecodeInvoiceTypeByCn(invoiceModelTemp.invoiceType) + "]");
                            grandChild.IsIdentifying = 1;
                            grandChild.Name = lastGroupName + "_" + grandChild.count + CommonUtil.getTreeModelNameTag(grandChild.nameTag);
                        }
                        if (isOCRSuccess.Equals(1))
                        {
                            grandChild.IsOCRSuccess = 1;
                            grandChild.IsClientOcr = 1;
                        }
                        else
                            grandChild.IsOCRSuccess = 2;

                        grandChild.Date = dateSec;
                        grandChild.IsExpanded = true;
                        grandChild.IsChecked = false;
                        grandChild.ImageUrl = imageUrl;
                        grandChild.Parent = newChild;
                        grandChild.level = 3;
                        grandChild.Barcode = "";
                        grandChild.InvoiceModelFun = invoiceModelTemp;

                        newChild.IsExpanded = true;
                        tvc.Dispatcher.Invoke(new Action(() =>
                        {
                            newChild.Children.Add(grandChild);
                        }));
                        //newChild.Children.Add(grandChild);

                        //ZsmTreeView.s_selectedTreeModel = grandChild;
                        //ZsmTreeView.s_selectedTreeModel.IsSelected = true;
                    }
                }
            }
            catch (Exception ex)
            {
                //busyIndicator.IsBusy = false;
                scanpageCountFail++;
                CommonUtil.WriteLog(ex);
                return;
            }
            #endregion
            #endregion
        }

        /// <summary>
        /// 是否能上传
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void shangchuan_Click(object sender, RoutedEventArgs e)
        {
            #region
            try
            {
                IList<TreeModel> lv2List = tvc.Level2Items();
                IList<TreeModel> lv3List = tvc.Level3Items();

                IEnumerator<TreeModel> enumerator = lv2List.GetEnumerator();
                CanUploadData model = null;
                while (enumerator.MoveNext())
                {
                    TreeModel groupItem = enumerator.Current;

                    Dictionary<string, string> paramsDic = new Dictionary<string, string>();
                    paramsDic.Add("ticketId", Global.getInstance().loginData.data.ticketId);
                    paramsDic.Add("imageType", groupItem.Type);
                    paramsDic.Add("imageCode", groupItem.imageCode);
                    paramsDic.Add("buDanNodeType", "0");

                    if (groupItem.Children.Count == 0)
                    {
                        groupItem.UploadRes = "错误：影像数量为0，不允许上传！";
                        continue;
                    }

                    //校验是否能够上传-补单不用校验，默认可以上传
                    String strResult = "";
                    if (groupItem.isBiSaoType.Equals(1))
                    {
                        groupItem.UploadRes = "可以上传";
                        continue;
                    }
                    else
                    {
                        strResult = CommonUtil.MssPost(Global.getInstance().strUrl + Global.getInstance().strCanUpload, paramsDic);
                    }

                    //获取返回信息
                    var ms = new MemoryStream(Encoding.UTF8.GetBytes(strResult));
                    {
                        DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(CanUploadData));
                        model = (CanUploadData)deseralizer.ReadObject(ms);// //反序列化ReadObject
                    }

                    //fail不能上传
                    if (model.code.Equals("Fail"))
                    {
                        groupItem.UploadRes = "该单不允许上传!";
                        if (model.message.Equals("") || model.message != null)
                        {
                            groupItem.UploadRes = "错误：" + model.message;
                        }
                        continue;
                    }

                    if (model.code.Equals("Error"))
                    {
                        if (model.message.Equals("") || model.message != null)
                        {
                            groupItem.UploadRes = "错误：" + "程序内部出错";
                            CommonUtil.WriteLogStr("表单上传校验时出错，异常信息：" + model.message, "shangchuan_Click");
                        }
                        continue;
                    }

                    if (model.code.Equals("Success"))
                    {
                        if (model.message.Equals("") || model.message != null)
                        {
                            groupItem.UploadRes = "可以上传";
                        }
                        continue;
                    }
                }

                UploadDlg dlg = new UploadDlg(lv2List, lv3List);
                dlg.Owner = this;
                dlg.UpGroupDelegateObj += (IList<GroupModel> groupList) =>
                {
                    //动态代理，把处理结果返回，执行UploadImageGroup()方法
                    UploadImageGroup(groupList);
                };
                dlg.ShowDialog();
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                return;
            }
            #endregion
        }

        /// <summary>
        /// 上传失败的单据，加载到原来的目录下
        /// </summary>
        /// <param name="temp"></param>
        private void UploadFailToAddTree(IList<GroupModel> temp)
        {
            #region
            List<String> failIdList = new List<string>();
            foreach (GroupModel g in temp)
            {
                if (g.logMark.Equals(2))
                {
                    failIdList.Add(g.Id);
                }
            }
            if (failIdList.Count.Equals(0))
            {
                return;
            }
            //“不支持从调度程序线程以外的线程对其 SourceCollection 进行的更改”的解决方法
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                System.Threading.SynchronizationContext.SetSynchronizationContext(new
                    System.Windows.Threading.DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
                System.Threading.SynchronizationContext.Current.Post(pl =>
                {
                    //里面写主要的逻辑
                    foreach (string id in failIdList)
                    {
                        foreach (TreeModel t in checkLv2ItemTemp)
                        {
                            if (t.isFail.Equals(1))
                            {
                                t.Parent.Children.Add(t);
                                continue;
                            }
                            if (t.Id.Equals(id))
                            {
                                t.nameTag.Add("[上传失败]");
                                t.Name = t.imageCode + CommonUtil.getTreeModelNameTag(t.nameTag);
                                t.isFail = 1;
                                t.Parent.Children.Add(t);
                            }
                        }
                    }
                }, null);
            });
            
            #endregion
        }

        private int FailCount = 0;      //上传失败次数
        private int SucceseCount = 0;   //上传成功次数
        /// <summary>
        /// 上传图片主逻辑
        /// </summary>
        /// <param name="groupList"></param>
        private void UploadImageGroup(IList<GroupModel> groupList)
        {
            #region
            deleteCheckTree(groupList);//上传时删除选择的分组，并且清空当前的图片显示
            FailCount = 0;//上传失败的单据数
            SucceseCount = 0;//上传成功的单据数
            CanUploadData model = null;
            int countIndex = 1;//单据序号中间变量

            foreach (GroupModel now in groupList)
            {
                now.UploadResult = "正在上传中...";
                SucceseListModel sl = new SucceseListModel();
                sl.Group = now.ImageCode;
                sl.Count = now.TreeList.Count;
                sl.Status = "等待上传...";
                sl.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                sl.Index = countIndex;
                countIndex++;
                nowListData.Add(sl);
            }
            _groupToDelList.Clear();
            //保存本次上传记录
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (o, a) =>
            {
                Object obj = new Object();
                Object LockerA = new Object();
                Object Locker = new Object();
                IEnumerator<GroupModel> enumerator = groupList.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    //获取每一个分组-groupItem
                    GroupModel groupItem = enumerator.Current;
                    try
                    {
                        model = CommonUtil.GetFtpUploadPath(groupItem);
                        //设置参数
                        string strParam = "";
                        List<ImagesData> imgsDataList = new List<ImagesData>();
                        List<InvoiceModel> InvoiceModelList = new List<InvoiceModel>();
                        Dictionary<string, string> imageDic = new Dictionary<string, string>();
                        Dictionary<string, string> syncUpResDic = new Dictionary<string, string>();

                        LoginData ftpData = CommonUtil.GetFtpData(groupItem);

                        //fail不能上传
                        if (null != ftpData && ftpData.code.Equals("Fail"))
                        {
                            if (ftpData.message.Equals("") || ftpData.message != null)
                                groupItem.UploadResult = "该表单不允许上传" + "原因：" + ftpData.message;

                            groupItem.logMark = 2;
                            _groupToDelList.Add(groupItem);
                            FailCount++;
                            DeleteUploadingInfo(groupItem);
                            UploadFailToAddTree(_groupToDelList);
                            continue;
                        }
                        String usernameTemp = "";
                        userNameCN.Dispatcher.Invoke(new Action(() =>
                        {
                            usernameTemp = userNameCN.Content.ToString();
                        }));
                        syncUpResDic.Add("ticketId", Global.getInstance().loginData.data.ticketId);
                        syncUpResDic.Add("ftpId", ftpData.data.ftpId);
                        syncUpResDic.Add("imageType", groupItem.type);
                        syncUpResDic.Add("username", usernameTemp);
                        
                        syncUpResDic.Add("imageCode", groupItem.ImageCode);

                        if (groupItem.isBuSaoTag.Equals(1))
                            syncUpResDic.Add("bizId", groupItem.bizId);
                        else
                            syncUpResDic.Add("bizId", "");

                        //报账单或者发票才需要送ocr
                        Boolean OCRNeedUpload = CommonUtil.GetOCRNeedUpload(groupItem.ImageCode);

                        //获取单号对应的ftp数据
                        string ftpIp = ftpData.data.ftpIp;
                        int ftpPort = ftpData.data.ftpPort;
                        string ftpUserName = ftpData.data.ftpUserName;
                        string ftpPassword = ftpData.data.ftpPassword;

                        List<String> twoDirList = CommonUtil.FthPathDecode(model.data.ftpPath);

                        int countUploadSync = 1;

                        //开始上传
                        foreach (TreeModel treeItem in groupItem.TreeList)
                        {
                            #region 数据先按上传顺序添加到数组
                            FileInfo fileInfo = new FileInfo(treeItem.ImageUrl);
                            string imageUrl = "";
                            string uploadImageName = "";//用来拼接ftp的imageUrl路径
                            if (groupItem.isBuSaoTag.Equals(1))
                                uploadImageName = groupItem.reqCode;
                            else
                                uploadImageName = groupItem.ImageCode;
                            //数据先按上传顺序添加到数组
                            //补单的数据
                            if (treeItem.isBuSaoTag.Equals(1))
                            {
                                // 拼接完整的图像路径,用于存储数据库
                                // 根据服务端返回的格式拼接路径，拼接完整的图像路径，用于存储数据库
                                string[] pathStr1 = model.data.ftpPath.Split('/');
                                if (pathStr1.Length != 1)
                                    imageUrl = "/" + uploadImageName + fileInfo.Name;
                                else
                                    imageUrl = "\\" + uploadImageName + fileInfo.Name;

                                //补单单号和数据
                                Console.WriteLine("scantime:"+treeItem.imageScanTime);
                                imgsDataList.Add(OcrUtil.SetImagesData(treeItem, model.data.ftpPath + imageUrl));

                                if (groupItem.insertTag)
                                {
                                    String insertImages = CommonUtil.getInsertImagesString(groupItem.TreeList);
                                    syncUpResDic.Remove("insertImages");
                                    syncUpResDic.Add("insertImages", insertImages);
                                }

                                syncUpResDic.Remove("repImageCode");
                                syncUpResDic.Add("repImageCode", treeItem.repImageCode);
                                
                            }
                            //正常上传的单据
                            if(!groupItem.isBuSaoTag.Equals(1))
                            {
                                syncUpResDic.Remove("repImageCode");
                                syncUpResDic.Add("repImageCode", "0");

                                // 根据服务端返回的格式拼接路径，拼接完整的图像路径，用于存储数据库
                                string[] pathStr1 = model.data.ftpPath.Split('/');
                                if (pathStr1.Length != 1)
                                    imageUrl = "/" + uploadImageName + fileInfo.Name;
                                else
                                    imageUrl = "\\" + uploadImageName + fileInfo.Name;

                                imgsDataList.Add(OcrUtil.SetImagesData(treeItem, model.data.ftpPath + imageUrl));
                            }
                            #endregion

                            #region 线程池处理上传图像，同步数据
                            ThreadPool.SetMaxThreads(2,8);
                            ThreadPool.QueueUserWorkItem(h =>
                            {
                                Thread.Sleep(10);
                                
                                if (null != treeItem && !treeItem.ImageUrl.Equals(""))
                                {
                                    //补单任务ftp操作：1-删除，2-补扫上传影像，其他影像不做操作
                                    if (groupItem.isBuSaoTag.Equals(1))
                                    {
                                        //标识影像删除
                                        if (treeItem.isDelete.Equals(1))
                                        {
                                            //删除操作逻辑-20171226 不删除ftp服务器上的图片
                                            //FtpHelper.Instance.deleteImage(Global.getInstance().loginData.data.ftpUserName, Global.getInstance().loginData.data.ftpPassword, Global.getInstance().loginData.data.ftpIp ,treeItem.ftpUrl);
                                            //更新数据库影像数量
                                            lock (Locker)
                                            {
                                                imageDic.Clear();
                                                imageDic.Add("password", "password");
                                                imageDic.Add("account", usernameTemp);
                                                imageDic.Add("functionType", "deleteImage");
                                                imageDic.Add("image_code", treeItem.imageCode + "," + treeItem.repImageCode);
                                                imageDic.Add("bizType", treeItem.Parent.Type);
                                                imageDic.Add("imageId", treeItem.Id);
                                                imageDic.Add("bizId", treeItem.bizId);
                                            }
                                            
                                            //同步数据库信息，删除数据
                                            string strResultImage = CommonUtil.buDanPost(Global.getInstance().strUrl + Global.getInstance().strBuDanInfo, imageDic);
                                            syncUpResDic.Remove("repImageCode");
                                            syncUpResDic.Add("repImageCode", treeItem.repImageCode);
                                            //continue;
                                        }
                                        //标识补扫上传操作
                                        if (treeItem.isBuSaoTag.Equals(1))
                                        {
                                            if (groupItem.isBuSaoTag.Equals(1))
                                                uploadImageName = groupItem.reqCode;
                                            else
                                                uploadImageName = groupItem.ImageCode;

                                            //上传
                                            if (upLoadTypeTag.Equals(1))
                                            {
                                                //saveStatus = CommonUtil.testWinScp(session, model.data.ftpPath, treeItem.ImageUrl, uploadImageName + fileInfo.Name);
                                                saveStatus = FtpHelper.Instance.newUploadFun(ftpIp, ftpPort, ftpUserName, ftpPassword, upLoadModel, twoDirList, uploadImageName, treeItem.ImageUrl);
                                            }
                                            else
                                                CommonUtil.uploadImageByWeb(fileInfo, treeItem.Parent.imageCode, "uploadImageByWeb", treeItem.Parent.imageCode, treeItem.Parent.Type, usernameTemp);

                                            if (OCRNeedUpload)
                                            {
                                                //保存一份到OCR ftp服务器-传图像的base64字节流到服务端，由服务端上传（网络原因）
                                                CommonUtil.uploadImageByWeb(fileInfo, treeItem.Parent.imageCode, "uploadOCR", treeItem.Parent.imageCode, treeItem.Parent.Type, usernameTemp);
                                            }
                                        }
                                    }
                                    //正常上传操作
                                    else
                                    {
                                        Console.WriteLine("scantimeNolmor:" + treeItem.imageScanTime);
                                        if (groupItem.isBuSaoTag.Equals(1))
                                            uploadImageName = groupItem.reqCode;
                                        else
                                            uploadImageName = groupItem.ImageCode;

                                        if (upLoadTypeTag.Equals(1))//上传文件到ftp服务器
                                        {
                                            //saveStatus = CommonUtil.testWinScp(session, model.data.ftpPath, treeItem.ImageUrl, uploadImageName + fileInfo.Name);
                                            saveStatus = FtpHelper.Instance.newUploadFun(ftpIp, ftpPort, ftpUserName, ftpPassword, upLoadModel, twoDirList, uploadImageName, treeItem.ImageUrl);
                                        }
                                        else//通过应用端来上传图像
                                            CommonUtil.uploadImageByWeb(fileInfo, treeItem.Parent.imageCode, "uploadImageByWeb", treeItem.Parent.imageCode, treeItem.Parent.Type, usernameTemp);

                                        //识别不出来 或者 发票是普通发票就送应用ocr
                                        //添加ocr区分开关
                                        if (OCRTrigger.Equals("true"))
                                        {
                                            //三个条件：需要上传发票，是普票，识别为发票
                                            //识别为普通发票
                                            //if (1 == OCRNeedUpload && treeItem.InvoiceModelFun.invoiceType.Equals("0104"))
                                            //    CommonUtil.uploadImageByWeb(fileInfo, treeItem.Parent.imageCode, "uploadOCR", treeItem.Parent.imageCode, treeItem.Parent.Type);
                                            //没有识别出具体信息，但是识别出是发票
                                            //if (treeItem.IsOCRSuccess.Equals(2) && treeItem.IsIdentifying.Equals(1) && !treeItem.InvoiceModelFun.invoiceType.Equals("0104"))
                                            if (treeItem.IsOCRSuccess.Equals(2) && treeItem.IsIdentifying.Equals(1))
                                            {
                                                CommonUtil.uploadImageByWeb(fileInfo, treeItem.Parent.imageCode, "uploadOCR", treeItem.Parent.imageCode, treeItem.Parent.Type, usernameTemp);
                                            }
                                        }
                                        else
                                        {
                                            if (OCRNeedUpload)
                                                CommonUtil.uploadImageByWeb(fileInfo, treeItem.Parent.imageCode, "uploadOCR", treeItem.Parent.imageCode, treeItem.Parent.Type, usernameTemp);
                                            Console.WriteLine("ocr上传结束"+ countUploadSync);
                                        }
                                    }
                                }
                                
                                lock (obj)
                                {
                                    foreach (SucceseListModel sl in nowListData)
                                    {
                                        if (sl.Group.Equals(groupItem.ImageCode))
                                        {
                                            sl.Status = "上传进度：" + countUploadSync.ToString() + "/" + groupItem.TreeList.Count.ToString();
                                            break;
                                        }
                                    }
                                }
                                lock (LockerA)
                                {
                                    if (countUploadSync.ToString().Equals(groupItem.TreeList.Count.ToString()))
                                    {
                                        strParam = CommonUtil.formatJson(imgsDataList);
                                        syncUpResDic.Add("images", strParam);

                                        //saveStatus状态码 0-连接失败，1-连接成功，2-连接超时
                                        if (2 == saveStatus)
                                        {
                                            //Object locker = new Object();
                                            //lock (locker)
                                            //{
                                                CommonUtil.ShowMsgFrom("单号[" + groupItem.ImageCode + "]上传失败!详情请查看结果");
                                                groupItem.UploadResult = "单号对应的FTP[" + ftpData.data.ftpIp + "]连接超时了，请联系网络管理员咨询！";
                                                writeListViewData(2, groupItem);
                                                groupItem.logMark = 2;//上传失败
                                                _groupToDelList.Add(groupItem);
                                                FailCount++;
                                                UploadFailToAddTree(_groupToDelList);
                                                DeleteUploadingInfo(groupItem);
                                            //}
                                        }
                                        else if (0 == saveStatus)
                                        {
                                            groupItem.UploadResult = "对应的FTP[" + ftpData.data.ftpIp + "]连接不上，请联系网络管理员咨询！";
                                            writeListViewData(2, groupItem);
                                            groupItem.logMark = 2;//上传失败
                                            _groupToDelList.Add(groupItem);
                                            UploadFailToAddTree(_groupToDelList);
                                            DeleteUploadingInfo(groupItem);
                                            FailCount++;
                                            //nowGroupList.Add(groupItem);
                                        }
                                        else
                                        {
                                            //保存日志-更新影像数量
                                            String strResult1 = CommonUtil.MssPost(Global.getInstance().strUrl + Global.getInstance().strSyncUpload, syncUpResDic);

                                            if ("error" == strResult1 || null == strResult1 || "" == strResult1)
                                            {
                                                //Object locker = new Object();
                                                //lock (locker)
                                                //{
                                                    CommonUtil.ShowMsgFrom("单号[" + groupItem.ImageCode + "]同步数据超时或者服务端返回异常，请稍后再试...");
                                                    writeListViewData(2, groupItem);//重置结果界面上传失败状态
                                                    groupItem.UploadResult = "同步数据时服务端返回出错，请稍后再试...错误代码：500";
                                                    groupItem.logMark = 2;
                                                    FailCount++;
                                                    _groupToDelList.Add(groupItem);
                                                    //nowGroupList.Add(groupItem);
                                                    UploadFailToAddTree(_groupToDelList);
                                                    DeleteUploadingInfo(groupItem);
                                                //}
                                            }
                                            else
                                            {
                                                //lock (locker)
                                                //{
                                                    SyncUploadResultData sURData;
                                                    var ms1 = new MemoryStream(Encoding.UTF8.GetBytes(strResult1));
                                                    {
                                                        DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(SyncUploadResultData));
                                                        sURData = (SyncUploadResultData)deseralizer.ReadObject(ms1);// //反序列化ReadObject
                                                    }
                                                    groupItem.logMark = 1;//先记录成功的标识，后面根据条件来改变
                                                    writeListViewData(1, groupItem);
                                                    SucceseCount++;//先把成功的count加1，后面根据条件来改变

                                                    if (null == sURData)
                                                    {
                                                        CommonUtil.ShowMsgFrom("单号[" + groupItem.ImageCode + "]同步数据超时或者服务端返回异常，请稍后再试...");
                                                        sURData.message = "同步数据超时或者服务端返回异常，请稍后再试...";
                                                        groupItem.logMark = 2;
                                                        SucceseCount--;
                                                        FailCount++;
                                                        _groupToDelList.Add(groupItem);
                                                        UploadFailToAddTree(_groupToDelList);
                                                    }
                                                    else if ("Error".Equals(sURData.code))
                                                    {
                                                        CommonUtil.ShowMsgFrom("单号[" + groupItem.ImageCode + "]同步数据出错");
                                                        writeListViewData(2, groupItem);
                                                        CommonUtil.WriteLogStr("同步数据出错，异常信息：" + sURData.message, "UploadImageGroup");
                                                        sURData.message = "操作超时或者服务端返回异常，请稍后再试...";
                                                        groupItem.logMark = 2;
                                                        SucceseCount--;
                                                        FailCount++;
                                                        _groupToDelList.Add(groupItem);
                                                        UploadFailToAddTree(_groupToDelList);
                                                    }
                                                    else { }
                                                    groupItem.UploadResult = sURData.message;
                                                    _groupToDelList.Add(groupItem);
                                                    DeleteUploadingInfo(groupItem);
                                                    CommonUtil.ShowMsgFrom("单号[" + groupItem.ImageCode + "]上传成功!");
                                                //}
                                            }
                                        }
                                    }

                                    if (!countUploadSync.ToString().Equals(groupItem.TreeList.Count.ToString()))
                                    {
                                        countUploadSync++;
                                        Console.WriteLine("countUploadSync:" + countUploadSync);
                                    }
                                }
                            });
                            #endregion
                        }
                    }
                    catch (Exception ex)
                    {
                        writeListViewData(2,groupItem);
                        CommonUtil.WriteLog(ex);
                        FailCount++;
                        groupItem.UploadResult = ex.Message + "，请稍后再试...";
                        groupItem.logMark = 2;
                        _groupToDelList.Add(groupItem);
                        DeleteUploadingInfo(groupItem);
                        continue;
                    }
                }
            };

            //上传操作完成后
            worker.RunWorkerCompleted += (o, a) =>
            {
                //上传结果弹出小窗口提示
                //保存本次上传记录
                //saveNowUploadResult((string)username.Content, nowGroupList);
                //保存上传记录的缓存
                //saveUploadResult((string)username.Content, _groupToDelList);
            };
            worker.RunWorkerAsync();
            #endregion
        }

        /// <summary>
        /// 删除结果界面中已经上传结束的记录：成功/不成功
        /// </summary>
        /// <param name="groupItem"></param>
        private void DeleteUploadingInfo(GroupModel groupItem)
        {
            Object locker = new Object();
            lock (locker)
            {
                //从调度程序线程执行操作
                ThreadPool.QueueUserWorkItem(delegate
                {
                    System.Threading.SynchronizationContext.SetSynchronizationContext(new
                        System.Windows.Threading.DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
                    System.Threading.SynchronizationContext.Current.Post(pl =>
                    {
                        //删除上传完成的任务
                        foreach (SucceseListModel sl in nowListData)
                        {
                            if (sl.Group.Equals(groupItem.ImageCode))
                            {
                                if (sl.logMark.Equals(1))
                                {
                                    sl.Status = "同步完成";
                                    succeseListDate.Insert(0, sl);
                                }
                                if (sl.logMark.Equals(2))
                                {
                                    sl.Status = groupItem.UploadResult;
                                    failListDate.Insert(0, sl);
                                }
                                nowListData.Remove(sl);//上传完移除
                                saveUploadResult((string)userNameCN.Content, _groupToDelList);//保存一次上传结果，同步变量数据
                                break;
                            }
                        }
                    }, null);
                });
            }
        }

        public void writeListViewData(int logMark,GroupModel groupItem)
        {
            Object obj = new Object();
            lock (obj)
            {
                foreach (SucceseListModel sl in nowListData)
                {
                    if (sl.Group.Equals(groupItem.ImageCode))
                    {
                        sl.logMark = logMark;
                        break;
                    }
                }
            }
        }

        #region 缩小放大
        private void fangda_Click(object sender, RoutedEventArgs e)
        {
            var point = new System.Windows.Point();
            var actualPoint = group.Inverse.Transform(point); // 想要缩放的点
            slider.Value = slider.Value + 0.1;
            tt.X = -((actualPoint.X * (slider.Value - 1))) + point.X - actualPoint.X;
            tt.Y = -((actualPoint.Y * (slider.Value - 1))) + point.Y - actualPoint.Y;
        }

        private void suoxiao_Click(object sender, RoutedEventArgs e)
        {
            var point = new System.Windows.Point();
            var actualPoint = group.Inverse.Transform(point); // 想要缩放的点
            slider.Value = slider.Value - 0.1;
            tt.X = -((actualPoint.X * (slider.Value - 1))) + point.X - actualPoint.X;
            tt.Y = -((actualPoint.Y * (slider.Value - 1))) + point.Y - actualPoint.Y;
        }
        #endregion

        private void zuozhuan_Click(object sender, RoutedEventArgs e)
        {
            #region
            try
            {


                if (null == ZsmTreeView.s_selectedTreeModel || null == ZsmTreeView.s_selectedTreeModel.ImageUrl)
                {
                    CMessageBox.Show("请选择具体的图像！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                    return;
                }

                String strPath = ZsmTreeView.s_selectedTreeModel.ImageUrl;

                FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.ReadWrite);
                System.Drawing.Image img = System.Drawing.Image.FromStream(fs);
                fs.Close();

                Bitmap bitmap = new Bitmap(img);
                bitmap = Rotate(bitmap, 90);

                IntPtr hbitmap = bitmap.GetHbitmap();
                BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                                                  hbitmap,
                                                  IntPtr.Zero,
                                                  Int32Rect.Empty,
                                                  BitmapSizeOptions.FromEmptyOptions());
                MainImage.Source = bitmapSource;

                File.Delete(ZsmTreeView.s_selectedTreeModel.ImageUrl);

                BitmapEncoder encoder = new JpegBitmapEncoder();
                FileStream destStream = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.Write);
                encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                encoder.Save(destStream);
                destStream.Close();
                CommonUtil.ClearMemory();
                Gdi32Native.DeleteObject(hbitmap);
                GC.Collect(); //强制回收资源  
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
            }
            #endregion
        }

        private void youzhuan_Click(object sender, RoutedEventArgs e)
        {
            #region
            try
            {
                if (null == ZsmTreeView.s_selectedTreeModel || null == ZsmTreeView.s_selectedTreeModel.ImageUrl)
                {
                    CMessageBox.Show("请选择具体的图像！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                    return;
                }

                String strPath = ZsmTreeView.s_selectedTreeModel.ImageUrl;

                FileStream fs = new FileStream(strPath, FileMode.Open, FileAccess.ReadWrite);
                System.Drawing.Image img = System.Drawing.Image.FromStream(fs);
                fs.Close();

                Bitmap bitmap = new Bitmap(img);
                bitmap = Rotate(bitmap, -90);
                IntPtr hbitmap = bitmap.GetHbitmap();
                BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
                                                  hbitmap,
                                                  IntPtr.Zero,
                                                  Int32Rect.Empty,
                                                  BitmapSizeOptions.FromEmptyOptions());

                MainImage.Source = bitmapSource;

                File.Delete(ZsmTreeView.s_selectedTreeModel.ImageUrl);

                BitmapEncoder encoder = new JpegBitmapEncoder();
                FileStream destStream = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.Write);
                encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                encoder.Save(destStream);
                destStream.Close();
                CommonUtil.ClearMemory();
                Gdi32Native.DeleteObject(hbitmap);
                GC.Collect(); //强制回收资源 
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
            }
            #endregion
        }

        private void shuaxin_Click(object sender, RoutedEventArgs e)
        {
            slider.Value = 0;
            tt.X = 0;
            tt.Y = 0;
        }

        IList<TreeModel> checkLv2ItemTemp = new List<TreeModel>();//用于处理上传失败的情况
        private void deleteCheckTree(IList<GroupModel> groupList)
        {
            #region
            //---start   按照需求：上传时删除选择的分组  
            checkLv2ItemTemp = tvc.Level2Items();
            
            for (int i=0;i<groupList.Count;i++)
            {
                foreach (TreeModel g in checkLv2ItemTemp)
                {
                    if (groupList[i].Id.Equals(g.Id))
                    {
                        TreeModel groupItemParent = g.Parent;
                        groupItemParent.Children.Remove(g);
                    }
                }
            }
            //清空当前的图片显示-给一个空的BitmapImage
            ZsmTreeView.s_selectedTreeModel = m_treeList[0];
            MainImage.Source = null;
            //---end
            #endregion
        }

        /// <summary>
        /// 选择删除
        /// </summary>
        private void deleteTree()
        {
            #region
            if (3 == ZsmTreeView.s_selectedTreeModel.level && ZsmTreeView.s_selectedTreeModel.isBiSaoType.Equals(1) && ZsmTreeView.s_selectedTreeModel.isDelete.Equals(1))
            {
                CMessageBox.Show("抱歉，补单任务标识[删]的图像无需人为删除，请直接点击上传之后系统自动删除！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }
            //补单任务中，补扫进去或者上传进去的可以的删除
            if (3 == ZsmTreeView.s_selectedTreeModel.level
                && ZsmTreeView.s_selectedTreeModel.isBuSaoTag.Equals(1)
                && ZsmTreeView.s_selectedTreeModel.isDelete.Equals(2))
            {
                TreeModel parentTree = ZsmTreeView.s_selectedTreeModel.Parent;
                int xuhao = 1;
                //删除选择的图片
                parentTree.Children.Remove(ZsmTreeView.s_selectedTreeModel);
                foreach (TreeModel itemChild in parentTree.Children)
                {
                    itemChild.count = xuhao;
                    if (itemChild.Type.Equals("5"))
                        itemChild.Name = parentTree.imageCode + "-" + itemChild.count + CommonUtil.getTreeModelNameTag(itemChild.nameTag);
                    else
                        itemChild.Name = parentTree.repImageCode + "-" + itemChild.count + CommonUtil.getTreeModelNameTag(itemChild.nameTag);
                    xuhao++;
                }
                MainImage.Source = null;
                return;
            }
            //else if (2 == ZsmTreeView.s_selectedTreeModel.level && ZsmTreeView.s_selectedTreeModel.isBiSaoType.Equals(1))
            //{
            //    CMessageBox.Show("抱歉，补单任务不能删除！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
            //    return;
            //}
            else if (3 == ZsmTreeView.s_selectedTreeModel.level && ZsmTreeView.s_selectedTreeModel.isBiSaoType.Equals(1))
            {
                CMessageBox.Show("抱歉，补单任务图像不能删除！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }
            else { }

            if (null == ZsmTreeView.s_selectedTreeModel)
            {
                CMessageBox.Show("你还没有选择要删除的数据。", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }
            CMessageBoxResult cmr = CMessageBox.Show("是否要删除所选数据？", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
            if (cmr.Equals(CMessageBoxResult.OK))
            {
                //MainImage.Source = null;
                //选择根节点删除逻辑
                if (ZsmTreeView.s_selectedTreeModel.level == 1)
                {
                    ZsmTreeView.s_selectedTreeModel.Children.Clear();
                    MainImage.Source = null;
                    ZsmTreeView.s_selectedTreeModel = null;
                    return;
                }

                if (ZsmTreeView.s_selectedTreeModel.level == 2 || ZsmTreeView.s_selectedTreeModel.level == 3)
                {
                    TreeModel parentTree = ZsmTreeView.s_selectedTreeModel.Parent;
                    parentTree.Children.Remove(ZsmTreeView.s_selectedTreeModel);
                    if (ZsmTreeView.s_selectedTreeModel.level == 3)
                    {
                        int xuhao = 1;
                        foreach (TreeModel t in parentTree.Children)
                        {
                            t.count = xuhao;
                            t.Name = parentTree.Name + "-" + t.count + CommonUtil.getTreeModelNameTag(t.nameTag);
                            xuhao++;
                        }
                    }
                    ZsmTreeView.s_selectedTreeModel = null;
                    MainImage.Source = null;
                    return;
                }
            }
            #endregion
        }

        /// <summary>
        /// 删除勾选的数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deleteCheck_Click(object sender, RoutedEventArgs e)
        {
            #region
            CMessageBoxResult cmr = CMessageBox.Show("是否要删除所选数据？", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
            if (cmr == CMessageBoxResult.OK)
            {
                List<TreeModel> tempList = new List<TreeModel>();
                List<TreeModel> tempList2 = new List<TreeModel>();
                //记录要删除的三级目录
                foreach (TreeModel child1 in m_treeList)
                {
                    foreach (TreeModel child2 in child1.Children)
                    {
                        foreach (TreeModel child3 in child2.Children)
                        {
                            if (child3.IsChecked)
                            {
                                if (child3.isBiSaoType == 1 && child3.isDelete == 0)
                                {
                                    CMessageBox.Show("当前勾选的数据有补单限制删除的数据，请不要选择补单限制删除的数据。", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                                    return;
                                }
                                else
                                    tempList.Add(child3);
                            }
                        }
                    }
                }
                //删除三级目录
                for (int i = 0; i < tempList.Count; i++)
                {
                    foreach (TreeModel child1 in m_treeList)
                    {
                        foreach (TreeModel child2 in child1.Children)
                        {
                            if (child2.Children.Contains(tempList[i]))
                            {
                                child2.Children.Remove(tempList[i]);
                                break;
                            }
                        }
                    }
                }

                //记录要删除的二级目录
                foreach (TreeModel child1 in m_treeList)
                {
                    foreach (TreeModel child2 in child1.Children)
                    {
                        if (child2.IsChecked && child2.Children.Count == 0)
                        {
                            tempList2.Add(child2);
                        }
                    }
                }
                //删除二级目录
                for (int i = 0; i < tempList2.Count; i++)
                {
                    foreach (TreeModel child1 in m_treeList)
                    {
                        if (child1.Children.Contains(tempList2[i]))
                        {
                            child1.Children.Remove(tempList2[i]);
                            break;
                        }
                    }
                }

                //重新排序
                foreach (TreeModel item in m_treeList)
                {
                    foreach (TreeModel child in item.Children)
                    {
                        int count = 1;
                        for (int i = 0; i < child.Children.Count; i++)
                        {
                            child.Children[i].count = count;
                            if (child.isBiSaoType.Equals(1))
                                child.Children[i].Name = child.repImageCode + "-" + child.Children[i].count + CommonUtil.getTreeModelNameTag(child.Children[i].nameTag);
                            else
                                child.Children[i].Name = child.Name + "-" +child.Children[i].count + CommonUtil.getTreeModelNameTag(child.Children[i].nameTag);
                            count++;
                        }
                    }
                }
                ZsmTreeView.s_selectedTreeModel = null;
                MainImage.Source = null;
            }
            #endregion
        }

        private void shangyiye_Click(object sender, RoutedEventArgs e)
        {
            #region
            try
            {
                IList<TreeModel> treeList = tvc.Level3Items();
                int nPos = treeList.IndexOf(ZsmTreeView.s_selectedTreeModel);
                if (0 >= nPos || treeList.Count <= nPos) return;
                nPos--;
                ZsmTreeView.s_selectedTreeModel = treeList[nPos];
                if (!File.Exists(ZsmTreeView.s_selectedTreeModel.ImageUrl)) return;
                ZsmTreeView.s_selectedTreeModel.IsSelected = true;
                MainImage.Source = CommonUtil.Bitmap2BitmapImageFromImagrPath(ZsmTreeView.s_selectedTreeModel.ImageUrl);
                showGrid();
                
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                return;
            }
            #endregion
        }

        private void xiayiye_Click(object sender, RoutedEventArgs e)
        {
            #region
            try
            { 
                IList<TreeModel> treeList = tvc.Level3Items();
                int nPos = treeList.IndexOf(ZsmTreeView.s_selectedTreeModel);
                if (0 > nPos || treeList.Count - 1 <= nPos) return;
                nPos++;
                ZsmTreeView.s_selectedTreeModel = treeList[nPos];
                if (!File.Exists(ZsmTreeView.s_selectedTreeModel.ImageUrl)) return;
                ZsmTreeView.s_selectedTreeModel.IsSelected = true;
                MainImage.Source = CommonUtil.Bitmap2BitmapImageFromImagrPath(ZsmTreeView.s_selectedTreeModel.ImageUrl);
                showGrid();
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                return;
            }
            #endregion
        }

        private void grdMap_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            var point = e.GetPosition(grd); // 实际点击的点
            var actualPoint = group.Inverse.Transform(point); // 想要缩放的点
            slider.Value = slider.Value + (double)e.Delta / 1000;
            tt.X = -((actualPoint.X * (slider.Value - 1))) + point.X - actualPoint.X;
            tt.Y = -((actualPoint.Y * (slider.Value - 1))) + point.Y - actualPoint.Y;
        }

        public Bitmap Rotate(Bitmap b, int angle)
        {
            #region
            angle = angle % 360;
            //弧度转换
            double radian = angle * Math.PI / 180.0;
            double cos = Math.Cos(radian);
            double sin = Math.Sin(radian);
            //原图的宽和高
            int w = b.Width;
            int h = b.Height;
            int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
            int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
            //目标位图
            Bitmap dsImage = new Bitmap(W, H);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dsImage);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //计算偏移量
            System.Drawing.Point Offset = new System.Drawing.Point((W - w) / 2, (H - h) / 2);
            //构造图像显示区域：让图像的中心与窗口的中心点一致
            System.Drawing.Rectangle rect = new System.Drawing.Rectangle(Offset.X, Offset.Y, w, h);
            System.Drawing.Point center = new System.Drawing.Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
            g.TranslateTransform(center.X, center.Y);
            g.RotateTransform(360 - angle);
            //恢复图像在水平和垂直方向的平移
            g.TranslateTransform(-center.X, -center.Y);
            g.DrawImage(b, rect);
            //重至绘图的所有变换
            g.ResetTransform();
            g.Save();
            g.Dispose();
            //dsImage.Save("yuancd.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            return dsImage;
            #endregion
        }

        private void shezhi_Click(object sender, RoutedEventArgs e)
        {
            #region
            IList<string> sourceList;
            if (null != _twain)
            {
                sourceList = _twain.SourceNames;
            }
            else
            {
                sourceList = new List<string>();
            }
            SettingDlg dlg = new SettingDlg(m_bDetectBarcodeSetting, m_bDetectWhitePaperSetting, sourceList, m_configData.SourceListPos, m_configData.qualityValue);
            dlg.Owner = this;
            dlg.tiaoxingma_DelegateObj += () =>
            {
                if (m_bDetectBarcodeSetting)
                {
                    m_bDetectBarcodeSetting = false;
                }
                else
                {
                    m_bDetectBarcodeSetting = true;
                }
                m_bDetectBarcode = m_bDetectBarcodeSetting;
                m_bDetectWhitePaper = m_bDetectWhitePaperSetting;
            };

            dlg.kongbai_DelegateObj += () =>
            {
                if (m_bDetectWhitePaperSetting)
                {
                    m_bDetectWhitePaperSetting = false;
                }
                else
                {
                    m_bDetectWhitePaperSetting = true;
                }
                m_bDetectBarcode = m_bDetectBarcodeSetting;
                m_bDetectWhitePaper = m_bDetectWhitePaperSetting;
            };

            dlg.saomiaoyuan_DelegateObj += (int sourceListPos,long qualityValue) =>
            {
                m_configData.SourceListPos = sourceListPos;
                m_configData.qualityValue = qualityValue;
                this.qualityValue = qualityValue;
            };

            dlg.ShowDialog();
            #endregion
        }

        /// <summary>
        /// 保存用户数据
        /// </summary>
        private void SaveConfig()
        {
            #region
            ConfigData saveObj = new ConfigData();
            if (!File.Exists("C:\\MssClientCache\\urlSetting.xml"))
                CommonUtil.CreateAppSettingXml(Global.getInstance().strUrl);
            
            #region
            foreach (var tree in m_treeList)
            {
                ConfigData.Lv1Data lv1Data = new ConfigData.Lv1Data();

                lv1Data.id = tree.Id;
                lv1Data.name = tree.Name;
                lv1Data.level = 1;
                saveObj.dataList.Add(lv1Data);

                foreach (var child in tree.Children)
                {
                    ConfigData.Lv2Data lv2Data = new ConfigData.Lv2Data();

                    lv2Data.id = child.Id;
                    lv2Data.bizId = child.bizId;
                    lv2Data.isBiSaoType = child.isBiSaoType;
                    lv2Data.imageCode = child.imageCode;
                    lv2Data.name = child.Name;
                    lv2Data.isFail = child.isFail;
                    lv2Data.repImageCode = child.repImageCode;
                    lv2Data.Notation = child.Notation;
                    lv2Data.Description = child.Description;
                    lv2Data.evaResult = child.evaResult;
                    lv2Data.level = 2;
                    lv2Data.Type = child.Type;
                    lv2Data.Description = child.Description;
                    lv2Data.InsertTag = child.InsertTag;
                    lv2Data.isFail = child.isFail;
                    lv2Data.isNeedScan = child.isNeedScan;

                    lv1Data.dataList.Add(lv2Data);

                    foreach (var grandChild in child.Children)
                    {
                        ConfigData.Lv3Data lv3Data = new ConfigData.Lv3Data();
                        if (grandChild.InvoiceModelFun.invoiceCode!="" && grandChild.InvoiceModelFun.invoiceType != "")
                        {
                            lv3Data.invoiceCode = grandChild.InvoiceModelFun.invoiceCode;
                            lv3Data.invoiceContent = grandChild.InvoiceModelFun.invoiceContent;
                            lv3Data.invoiceNum = grandChild.InvoiceModelFun.invoiceNum;
                            lv3Data.invoiceDate = grandChild.InvoiceModelFun.invoiceDate;
                            lv3Data.invoiceType = grandChild.InvoiceModelFun.invoiceType;
                            lv3Data.amount = grandChild.InvoiceModelFun.amount;
                            lv3Data.sellerName = grandChild.InvoiceModelFun.sellerName;
                            lv3Data.totalAmount = grandChild.InvoiceModelFun.totalAmount;
                            lv3Data.checkCode = grandChild.InvoiceModelFun.checkCode;
                            lv3Data.buyerName = grandChild.InvoiceModelFun.buyerName;
                        }

                        lv3Data.id = grandChild.Id;
                        lv3Data.bizId = grandChild.bizId;
                        lv3Data.isBiSaoType = grandChild.isBiSaoType;
                        lv3Data.imageCode = grandChild.imageCode;
                        //string strName = System.Text.RegularExpressions.Regex.Replace(grandChild.Name, "[[合]]", "");
                        lv3Data.name = grandChild.Name;
                        lv3Data.count = grandChild.count;
                        lv3Data.repImageCode = grandChild.repImageCode;
                        lv3Data.isBuSaoTag = grandChild.isBuSaoTag;
                        lv3Data.isDelete = grandChild.isDelete;
                        lv3Data.Type = grandChild.Type;
                        lv3Data.ftpUrl = grandChild.ftpUrl;
                        lv3Data.level = 3;
                        lv3Data.isOCRSuccess = grandChild.IsOCRSuccess;
                        lv3Data.httpUrl = grandChild.httpUrl;
                        lv3Data.imageUrl = grandChild.ImageUrl;
                        lv3Data.imageName = grandChild.imageName;
                        lv3Data.isIdentifying = grandChild.IsIdentifying;
                        lv3Data.nametagList = grandChild.nameTag;

                        lv2Data.dataList.Add(lv3Data);
                    }
                }
            }
            #endregion

            saveObj.DetectBarcode = m_bDetectBarcodeSetting;
            saveObj.DetectWhitePaper = m_bDetectWhitePaperSetting;
            saveObj.SourceListPos = Global.getInstance().SourceListPos;
            saveObj.upLoadModel = upLoadModel;
            saveObj.upLoadType = upLoadTypeTag;
            saveObj.qualityValue = Global.getInstance().qualityValue;

            JavaScriptSerializer js = new JavaScriptSerializer();
            string strJson = js.Serialize(saveObj);//序列化
            string strFilePath = System.AppDomain.CurrentDomain.BaseDirectory + Global.getInstance().strConfigFileName;

            string fileName = userNameCN.Content.ToString() + "_config_"+Global.getInstance().sysTypeCode+".bin";
            string filePath = "C:/MssClientCache/";//缓存保存地址
            strFilePath = filePath + fileName;
            System.IO.File.WriteAllText(strFilePath, strJson);
            //MessageBox.Show(strJson);
            #endregion
        }

        /// <summary>
        /// 加载用户数据
        /// </summary>
        private void LoadConfig()
        {
            #region
            //string strFilePath = System.AppDomain.CurrentDomain.BaseDirectory + Global.getInstance().strConfigFileName;
            string strText = "";
            string strText2 = "";
            string fileName = userNameCN.Content.ToString() + "_config_" + Global.getInstance().sysTypeCode + ".bin";
            string filePath = "C:/MssClientCache/";//缓存保存地址
            string strFilePath = filePath + fileName;
            if (!File.Exists(strFilePath))
            {
                strText = "{\"dataList\":[{\"dataList\":[],\"id\":\"1\",\"level\":\"1\",\"name\":\"报帐单\",\"icon\":null,\"isChecked\":false,\"isExpanded\":true,\"date\":null,\"imageUrl\":null,\"barcode\":\"\"},{\"dataList\":[],\"id\":\"2\",\"level\":\"1\",\"name\":\"供应商发票\",\"icon\":null,\"isChecked\":false,\"isExpanded\":true,\"date\":null,\"imageUrl\":null,\"barcode\":\"\"},{\"dataList\":[],\"id\":\"3\",\"level\":\"1\",\"name\":\"合同\",\"icon\":null,\"isChecked\":false,\"isExpanded\":true,\"date\":null,\"imageUrl\":null,\"barcode\":\"\"},{\"dataList\":[],\"id\":\"4\",\"level\":\"1\",\"name\":\"承诺函\",\"icon\":null,\"isChecked\":false,\"isExpanded\":true,\"date\":null,\"imageUrl\":null,\"barcode\":\"\"},{\"dataList\":[],\"id\":\"5\",\"level\":\"1\",\"name\":\"零星扫描\",\"icon\":null,\"isChecked\":false,\"isExpanded\":true,\"date\":null,\"imageUrl\":null,\"barcode\":\"\"}],\"upLoadModel\":2,\"upLoadType\":1,\"qualityValue\":60,\"SourceListPos\":0,\"DetectBarcode\":true,\"DetectWhitePaper\":false}";
                System.IO.File.WriteAllText(strFilePath, strText);
            }
            else
            {
                strText = "{\"dataList\":[{\"dataList\":[],\"id\":\"1\",\"level\":\"1\",\"name\":\"报帐单\",\"icon\":null,\"isChecked\":false,\"isExpanded\":true,\"date\":null,\"imageUrl\":null,\"barcode\":\"\"},{\"dataList\":[],\"id\":\"2\",\"level\":\"1\",\"name\":\"供应商发票\",\"icon\":null,\"isChecked\":false,\"isExpanded\":true,\"date\":null,\"imageUrl\":null,\"barcode\":\"\"},{\"dataList\":[],\"id\":\"3\",\"level\":\"1\",\"name\":\"合同\",\"icon\":null,\"isChecked\":false,\"isExpanded\":true,\"date\":null,\"imageUrl\":null,\"barcode\":\"\"},{\"dataList\":[],\"id\":\"4\",\"level\":\"1\",\"name\":\"承诺函\",\"icon\":null,\"isChecked\":false,\"isExpanded\":true,\"date\":null,\"imageUrl\":null,\"barcode\":\"\"},{\"dataList\":[],\"id\":\"5\",\"level\":\"1\",\"name\":\"零星扫描\",\"icon\":null,\"isChecked\":false,\"isExpanded\":true,\"date\":null,\"imageUrl\":null,\"barcode\":\"\"}],\"upLoadModel\":2,\"upLoadType\":1,\"qualityValue\":60,\"SourceListPos\":0,\"DetectBarcode\":true,\"DetectWhitePaper\":false}";
            }
            //读取config配置文件
            strText2 = System.IO.File.ReadAllText(strFilePath);

            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(strText)))
            {
                DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(ConfigData));
                m_configData = (ConfigData)deseralizer.ReadObject(ms);// //反序列化ReadObject
            }
            ConfigData m_configData1 = new ConfigData();
            if (strText2 != "")
            {
                using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(strText2)))
                {
                    DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(ConfigData));
                    m_configData1 = (ConfigData)deseralizer.ReadObject(ms);// //反序列化ReadObject
                }
            }
            upLoadModel = m_configData1.upLoadModel;
            if (upLoadModel == 2)
            {
                upLoadModel = 2;
                ftpModel.Header = "主动模式";
            }
            else
            {
                upLoadModel = 1;
                ftpModel.Header = "被动模式";
            }

            upLoadTypeTag = m_configData1.upLoadType;
            if (upLoadTypeTag == 2)
            {
                ftpModel.IsEnabled = false;
                upLoadTypeTag = 2;
                upLoadType.Header = "应用上传";
            }
            else
            {
                upLoadTypeTag = 1;
                upLoadType.Header = "FTP上传";
            }

            if (m_configData1.qualityValue.Equals(0))
            {
                m_configData1.qualityValue = 60;
            }

            Global.getInstance().SourceListPos = m_configData1.SourceListPos;
            Global.getInstance().qualityValue = m_configData1.qualityValue;
            this.qualityValue = m_configData1.qualityValue;

            m_configData.SourceListPos = m_configData1.SourceListPos;
            m_configData.qualityValue = m_configData1.qualityValue;
            m_configData.DetectBarcode = m_configData1.DetectBarcode;
            m_configData.DetectBarcode = m_configData1.DetectWhitePaper;
            //m_configData.OcrTag = m_configData1.OcrTag;

            m_bDetectBarcodeSetting = m_configData1.DetectBarcode;
            m_bDetectWhitePaperSetting = m_configData1.DetectWhitePaper;
            m_bDetectBarcode = m_bDetectBarcodeSetting;
            m_bDetectWhitePaper = m_bDetectWhitePaperSetting;

            //加载左侧树形结构菜单
            foreach (var lv1Item in m_configData1.dataList)
            {
                TreeModel tree = new TreeModel();

                tree.Id = lv1Item.id;
                tree.level = 1;
                tree.Name = lv1Item.name;
                tree.Date = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                tree.IsChecked = false;
                tree.IsExpanded = true;

                foreach (var lv2Item in lv1Item.dataList)
                {
                    TreeModel child = new TreeModel();
                    child.Id = lv2Item.id;
                    child.Name = lv2Item.name;
                    child.Date = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    child.IsChecked = true;
                    child.IsExpanded = true;
                    child.isBiSaoType = lv2Item.isBiSaoType;
                    child.Type = lv2Item.Type;
                    child.repImageCode = lv2Item.repImageCode;
                    child.imageCode = lv2Item.imageCode;
                    child.isFail = lv2Item.isFail;
                    child.InsertTag = lv2Item.InsertTag;
                    child.level = 2;
                    child.isNeedScan = lv2Item.isNeedScan;
                    child.Description = lv2Item.Description;
                    child.Notation = lv2Item.Notation;
                    child.bizId = lv2Item.bizId;
                    child.evaResult = lv2Item.evaResult;
                    child.Parent = tree;

                    foreach (var lv3Item in lv2Item.dataList)
                    {
                        TreeModel grandChild = new TreeModel();
                        grandChild.Id = lv3Item.id;
                        grandChild.Name = lv3Item.name;
                        grandChild.Date = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        grandChild.IsChecked = true;
                        grandChild.IsExpanded = true;
                        grandChild.ImageUrl = lv3Item.imageUrl;
                        grandChild.isDelete = lv3Item.isDelete;
                        grandChild.isMerge = lv3Item.isMerge;
                        grandChild.isBuSaoTag = lv3Item.isBuSaoTag;
                        grandChild.isBiSaoType = lv3Item.isBiSaoType;
                        grandChild.count = lv3Item.count;
                        grandChild.httpUrl = lv3Item.httpUrl;
                        grandChild.ftpUrl = lv3Item.ftpUrl;
                        grandChild.level = 3;
                        grandChild.repImageCode = lv3Item.repImageCode;
                        grandChild.imageCode = lv3Item.imageCode;
                        grandChild.IsIdentifying = lv3Item.isIdentifying;
                        grandChild.nameTag = lv3Item.nametagList;
                        grandChild.IsOCRSuccess = lv3Item.isOCRSuccess;
                        grandChild.Type = lv3Item.Type;

                        grandChild.InvoiceModelFun.invoiceCode = lv3Item.invoiceCode;
                        grandChild.InvoiceModelFun.invoiceContent = lv3Item.invoiceContent;
                        grandChild.InvoiceModelFun.invoiceNum = lv3Item.invoiceNum;
                        grandChild.InvoiceModelFun.invoiceDate = lv3Item.invoiceDate;
                        grandChild.InvoiceModelFun.invoiceType = lv3Item.invoiceType;
                        grandChild.InvoiceModelFun.amount = lv3Item.amount;
                        grandChild.InvoiceModelFun.sellerName = lv3Item.sellerName;
                        grandChild.InvoiceModelFun.totalAmount = lv3Item.totalAmount;
                        grandChild.InvoiceModelFun.checkCode = lv3Item.checkCode;
                        grandChild.InvoiceModelFun.buyerName = lv3Item.buyerName;
                        grandChild.Parent = child;

                        child.Children.Add(grandChild);
                    }
                    tree.Children.Add(child);
                }
                m_treeList.Add(tree);
            }
            tvc.ItemsSourceData = m_treeList;
            #endregion
        }

        private void tuichu_Click(object sender, RoutedEventArgs e)
        {
            //CommonUtil.clearCache(0);
            SaveConfig();
            Process.GetCurrentProcess().Kill();
        }

        /// <summary>
        /// 关于面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void about_Click(object sender, RoutedEventArgs e)
        {
            AboutDlg aboutDlg = new AboutDlg();
            aboutDlg.ShowDialog();
        }

        /// <summary>
        /// 保存本次的上传内容 
        /// </summary>
        /// <param name="username"></param>
        /// <param name="list"></param>
        public void saveNowUploadResult(string username, IList<GroupModel> list)
        {
            #region
            string fileName = username + "_nowUploadResultData.bin";
            string filePath = "C:/MssClientCache/";//缓存保存地址
            Dictionary<string, ResultModel> ResultList = new Dictionary<string, ResultModel>();
            BinaryFormatter bf = new BinaryFormatter();
            if (!Directory.Exists(filePath))//判断文件夹是否存在 
            {
                Directory.CreateDirectory(filePath);//不存在则创建文件夹 
            }
            FileStream fs = new FileStream(filePath + fileName, FileMode.OpenOrCreate);
            int i = 1;
            //把list数据添加到data
            foreach (GroupModel group in list)
            {
                String dataTime = DateTime.Now.ToString("yyyyMMddHHmmssff");
                ResultModel resultModel = new ResultModel();
                resultModel.uploadResult = group.UploadResult;
                resultModel.imageCode = group.ImageCode;
                resultModel.type = group.type;
                resultModel.count = group.TreeList.Count;
                resultModel.date = System.DateTime.Now.ToString();
                resultModel.logMark = group.logMark;
                ResultList.Add(dataTime + i, resultModel);
                i++;
            }

            //关闭
            fs.Close();
            FileStream fsNew = new FileStream(filePath + fileName, FileMode.Create);
            //写入文件
            bf.Serialize(fsNew, ResultList);
            //关闭
            fsNew.Close();
            #endregion
        }

        /// <summary>
        /// 保存上传结果（只记录50(自定义)条结果）
        /// </summary>
        /// <param name="username"></param>
        /// <param name="list"></param>
        public void saveUploadResult(string username, IList<GroupModel> list)
        {
            #region
            // 登录时 如果没有resultData.bin文件就创建、有就打开
            string fileName = username + "_resultData.bin";
            string filePath = "C:/MssClientCache/";//缓存保存地址
            if (!Directory.Exists(filePath))//判断文件夹是否存在 
            {
                Directory.CreateDirectory(filePath);//不存在则创建文件夹 
            }
            FileStream fs = new FileStream(filePath + fileName, FileMode.OpenOrCreate);

            Dictionary<string, ResultModel> ResultList = new Dictionary<string, ResultModel>();
            BinaryFormatter bf = new BinaryFormatter();
            if (fs.Length > 0)
            {
                //读取原来的保存的数据
                ResultList = bf.Deserialize(fs) as Dictionary<string, ResultModel>;
            }

            if (ResultList.Count >= 60)
            {
                //获取原来的数据
                List<ResultModel> tempList = new List<ResultModel>();
                foreach (ResultModel group in ResultList.Values)
                {
                    tempList.Add(group);
                }
                //清空原来的数据
                ResultList.Clear();
                //获取后面十个数据
                List<ResultModel> resultModelList = new List<ResultModel>();
                for (int i = tempList.Count - 1; i >= 0; i--)
                {
                    ResultModel resultModel = new ResultModel();
                    resultModel = tempList[i];
                    System.Diagnostics.Debug.WriteLine(resultModel.date);
                    resultModelList.Add(resultModel);
                    int breakPiont = tempList.Count - 60;

                    if (i == breakPiont)
                    {
                        break;
                    }
                }
                //清空
                tempList.Clear();
                //在排列一次
                for (int i = resultModelList.Count - 1; i >= 0; i--)
                {
                    ResultModel resultModel = new ResultModel();
                    resultModel = resultModelList[i];
                    tempList.Add(resultModel);
                }
                foreach (ResultModel re in tempList)
                {
                    String dataTime = DateTime.Now.ToString("yyyyMMddHHmmssff");
                    //System.Diagnostics.Debug.WriteLine(dataTime + Guid.NewGuid().ToString());
                    ResultList.Add(dataTime + Guid.NewGuid().ToString(), re);
                }
            }
            //把list数据添加到data
            foreach (GroupModel group in list)
            {
                String dataTime = DateTime.Now.ToString("yyyyMMddHHmmssffff");
                ResultModel resultModel = new ResultModel();
                resultModel.uploadResult = group.UploadResult;
                resultModel.imageCode = group.ImageCode;
                resultModel.type = group.type;
                resultModel.count = group.TreeList.Count;
                resultModel.logMark = group.logMark;
                resultModel.date = System.DateTime.Now.ToString();
                ResultList.Add(dataTime + Guid.NewGuid().ToString(), resultModel);
            }
            //关闭
            fs.Close();
            FileStream fsNew = new FileStream(filePath + fileName, FileMode.Create);
            //写入文件
            bf.Serialize(fsNew, ResultList);
            //关闭
            fsNew.Close();
            #endregion
        }

        /// <summary>
        /// 点击结果按钮，显示最近的上传数据 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void showUploadResult_Click(object sender, RoutedEventArgs e)
        {

            this.listModle.PopupIsOpen = true;
            loadListViewData();
        }

        /// <summary>
        /// 加载上传缓存数据
        /// </summary>
        public void loadListViewData()
        {
            #region
            List<SucceseListModel> succeseTabDate = new List<SucceseListModel>();
            string fileName = remenberTheuserName + "_resultData.bin";
            string filePath = "C:/MssClientCache/";

            //登录时 如果没有resultData.bin文件就创建、有就打开
            FileStream fs = new FileStream(filePath + fileName, FileMode.OpenOrCreate);
            List<ResultModel> list = new List<ResultModel>();
            if (fs.Length > 0)
            {
                int countIndexSuccese = 1;
                int countIndexFail = 1;
                BinaryFormatter bf = new BinaryFormatter();
                Dictionary<string, ResultModel> ResultList;
                ResultList = bf.Deserialize(fs) as Dictionary<string, ResultModel>;
                List<GroupModel> tempList = new List<GroupModel>();
                if (ResultList.Count != 0)
                {
                    foreach (ResultModel group in ResultList.Values)
                    {
                        SucceseListModel sl = new SucceseListModel();
                        sl.Group = group.imageCode;
                        sl.Status = group.uploadResult;
                        sl.Date = group.date;
                        sl.logMark = group.logMark;
                        sl.Count = group.count;
                        succeseTabDate.Add(sl);
                    }
                    succeseTabDate.Reverse();
                    succeseListDate.Clear();
                    failListDate.Clear();
                    foreach (SucceseListModel sl in succeseTabDate)
                    {
                        if (sl.logMark.Equals(1))
                        {
                            sl.Index = countIndexSuccese;
                            countIndexSuccese++;
                            succeseListDate.Add(sl);
                        }
                        if (sl.logMark.Equals(2))
                        {
                            sl.Index = countIndexFail;
                            countIndexFail++;
                            failListDate.Add(sl);
                        }
                    }
                }
            }
            fs.Close();
            #endregion
        }

        /// <summary>
        /// 双击用户名复制
        /// </summary>
        private void username_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            #region
            try
            {
                
                string groupStr = (string)userNameCN.Content;
                Clipboard.SetDataObject(groupStr);
                CommonUtil.ShowMsgFrom("内容:[" + groupStr + "]已经复制到剪贴板");
            }
            catch (System.Exception ex)
            {
                CommonUtil.WriteLog(ex);
                return;
            }
            #endregion
        }

        string type = "f";//f-缩小，t-放大
        /// <summary>
        /// 初始化界面的尺寸
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            #region
            try
            {
                double titleHeight = SystemParameters.CaptionHeight;
                listBox.Width = this.ActualWidth - TreeViewBorder.ActualWidth - 20;
                listBox.Height = this.ActualHeight - 125;
                tvc.Height = this.ActualHeight - titleHeight - 35 - 55 - 10;
                MainImage.Height = this.ActualHeight - 123;
                TreeViewBorder.Height = this.ActualHeight - titleHeight - 35 - 25;
                grd.Height = this.ActualHeight - 123;
            }
            catch (Exception ex)
            {
                return;
            }
            #endregion
        }

        /// <summary>
        /// 清空图片缓存
        /// </summary>
        private void cacheDelete_Click(object sender, RoutedEventArgs e)
        {
            CommonUtil.clearCache(true,1);
        }

        /// <summary>
        /// 补单获取按钮逻辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buDanGet_Click(object sender, RoutedEventArgs e)
        {
            BudanInfoGet(true);
        }

        /// <summary>
        /// 补单获取
        /// </summary>
        /// <param name="openType">获取方式 true-客户端手动获取，false-自动获取</param>
        private void BudanInfoGet(bool openType)
        {
            #region
            try
            {
                int failCount = 0;
                Dictionary<string, string> paramsDic = new Dictionary<string, string>();
                paramsDic.Add("password", "password");
                userNameCN.Dispatcher.Invoke(new Action(() =>
                {
                    paramsDic.Add("account", userNameCN.Content.ToString());
                }));
                paramsDic.Add("functionType", "info");
                paramsDic.Add("image_code", "00");
                paramsDic.Add("bizType", "00");
                paramsDic.Add("imageId", "00");
                paramsDic.Add("bizId", "00");
                string strResult = CommonUtil.buDanPost(Global.getInstance().strUrl + Global.getInstance().strBuDanInfo, paramsDic);
                if (null == strResult || "" == strResult || "[]".Equals(strResult))
                {
                    CommonUtil.ShowMsgFrom("没有获取到补单信息，请稍后再试");
                    return;
                }
                List<ReplenishInfoData> replenishInfoDataList = new List<ReplenishInfoData>();
                ReplenishInfoData replenishInfo = new ReplenishInfoData();
                var ms = new MemoryStream(Encoding.UTF8.GetBytes(strResult));
                {
                    DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(List<ReplenishInfoData>));
                    replenishInfoDataList = (List<ReplenishInfoData>)deseralizer.ReadObject(ms);// //反序列化ReadObjects
                }
                if (replenishInfoDataList.Count != 0)
                {
                    List<ReplenishInfoData> newReplenishInfoDataList = new List<ReplenishInfoData>();

                    List<int> posList = new List<int>();//记录当前存在的补单数据位置
                    //筛选新的补单任务：如果存在就记录数组的位置，目的是获取当前存在补单数据
                    for (int r = 0; r < replenishInfoDataList.Count; r++)
                    {
                        foreach (TreeModel treeItem in m_treeList)
                        {
                            foreach (TreeModel child in treeItem.Children)
                            {
                                if (null != child.repImageCode || "" == child.repImageCode)
                                {
                                    if (child.repImageCode.Equals(replenishInfoDataList[r].rep_Image_Code))
                                        posList.Add(r);
                                }
                            }
                        }
                    }

                    //获取当前存在的补单
                    if (posList.Count != 0)
                    {
                        for (int p = 0; p < posList.Count; p++)
                        {
                            newReplenishInfoDataList.Add(replenishInfoDataList[posList[p]]);
                        }
                    }

                    //从新获取的补单数据删除已存在的补单数据
                    for (int t = 0; t < newReplenishInfoDataList.Count; t++)
                    {
                        replenishInfoDataList.Remove(newReplenishInfoDataList[t]);
                    }

                    if (replenishInfoDataList.Count != 0)
                    {
                        CMessageBoxResult cmr = CMessageBoxResult.OK;
                        if (openType)
                            cmr = CMessageBox.Show("捕获到：" + (replenishInfoDataList.Count - failCount) + " 个补单，点击[确定]下载图像。", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                        else
                            cmr = CMessageBoxResult.OK;

                        App.Current.Dispatcher.Invoke((Action)(() => 
                        {
                            CommonUtil.ShowMsgFrom("正在加载补单数据，请稍等...");
                        }));

                        if (cmr == CMessageBoxResult.OK)
                        {
                            BackgroundWorker worker = new BackgroundWorker();
                            worker.DoWork += (o, a) =>
                            {
                                int donwLoadFailCount = 0;
                                List<string> donwLoadInfoList = new List<string>();
                                string donwLoadInfo = "";
                                //多个补单任务处理
                                for (int n = 0; n < replenishInfoDataList.Count; n++)
                                {
                                    //设置ftp数据：根据单号，类型获取对应组织，在获取对应的ftp信息
                                    Dictionary<string, string> ftpSync = new Dictionary<string, string>();
                                    ftpSync.Add("password", "password");
                                    ftpSync.Add("account", "account");
                                    ftpSync.Add("functionType", "getFtpInfo");
                                    ftpSync.Add("image_code", replenishInfoDataList[n].main_Image_Code);
                                    ftpSync.Add("bizType", replenishInfoDataList[n].bizType);
                                    ftpSync.Add("imageId", "");
                                    ftpSync.Add("bizId", "");
                                    string ftpInfo = CommonUtil.buDanPost(Global.getInstance().strUrl + Global.getInstance().strBuDanInfo, ftpSync);
                                    LoginData ftpData = new LoginData();

                                    //获取返回信息
                                    var ftpMs = new MemoryStream(Encoding.UTF8.GetBytes(ftpInfo));
                                    {
                                        DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(LoginData));
                                        ftpData = (LoginData)deseralizer.ReadObject(ftpMs);// //反序列化ReadObject
                                    }
                                    if (ftpData.code.Equals("Fail"))
                                    {
                                        CommonUtil.WriteLogStr("单号" + replenishInfoDataList[n].main_Image_Code + "获取ftp信息出错", "buDanGet");
                                        failCount++;
                                        continue;
                                    }

                                    //设置ftp数据
                                    string ftpIp = ftpData.data.ftpIp;
                                    int ftpPort = ftpData.data.ftpPort;
                                    string ftpUserName = ftpData.data.ftpUserName;
                                    string ftpPassword = ftpData.data.ftpPassword;
                                    Console.WriteLine(ftpData.data.ftpIp);

                                    //根据获取的单号创建文件夹
                                    string filePath = @"C:\MssClientCache\imageCache\" + replenishInfoDataList[n].rep_Image_Code;//缓存保存地址
                                    if (!Directory.Exists(filePath))//判断文件夹是否存在 
                                        Directory.CreateDirectory(filePath);//不存在则创建文件夹 

                                    //获取bizType类型
                                    string bizType = replenishInfoDataList[n].bizType;
                                    Dictionary<string, string> imageDic = new Dictionary<string, string>();
                                    imageDic.Add("password", "password");
                                    userNameCN.Dispatcher.Invoke(new Action(() =>
                                    {
                                        imageDic.Add("account", userNameCN.Content.ToString());
                                    }));
                                    imageDic.Add("functionType", "getImages");
                                    imageDic.Add("image_code", replenishInfoDataList[n].main_Image_Code);
                                    imageDic.Add("bizType", replenishInfoDataList[n].bizType);
                                    //每一个补单任务获取一次影像信息
                                    string strResultImage = CommonUtil.buDanPost(Global.getInstance().strUrl + Global.getInstance().strBuDanInfo, imageDic);

                                    List<ImagesData> imageDataList = new List<ImagesData>();
                                    var ms1 = new MemoryStream(Encoding.UTF8.GetBytes(strResultImage));
                                    {
                                        DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(List<ImagesData>));
                                        imageDataList = (List<ImagesData>)deseralizer.ReadObject(ms1);// //反序列化ReadObject
                                    }

                                    #region
                                    foreach (TreeModel treeItem in m_treeList)
                                    {
                                        if (treeItem.Id.Equals(bizType))
                                        {
                                            //新建补单组
                                            TreeModel childParentAdd = new TreeModel();
                                            childParentAdd.imageCode = replenishInfoDataList[n].main_Image_Code;
                                            if (null == replenishInfoDataList[n].bizId)
                                                childParentAdd.bizId = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                                            else
                                                childParentAdd.bizId = replenishInfoDataList[n].bizId;

                                            childParentAdd.evaResult = replenishInfoDataList[n].eva_result;
                                            childParentAdd.Id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                                            childParentAdd.Type = bizType;
                                            childParentAdd.Name = replenishInfoDataList[n].rep_Image_Code + CommonUtil.getChiFromEvaResult(childParentAdd.evaResult);
                                            childParentAdd.repImageCode = replenishInfoDataList[n].rep_Image_Code;//子流程单号
                                            childParentAdd.isBiSaoType = 1; //补单标识
                                            childParentAdd.IsExpanded = true;
                                            childParentAdd.level = 2;
                                            childParentAdd.Parent = treeItem;
                                            childParentAdd.IsChecked = true;
                                            childParentAdd.isNeedScan = replenishInfoDataList[n].is_Need_Scan;
                                            childParentAdd.Description = replenishInfoDataList[n].reason_name;
                                            childParentAdd.Notation = replenishInfoDataList[n].remark;
                                            //“不支持从调度程序线程以外的线程对其 SourceCollection 进行的更改”的解决方法
                                            System.Threading.ThreadPool.QueueUserWorkItem(delegate
                                            {
                                                System.Threading.SynchronizationContext.SetSynchronizationContext(new
                                                    System.Windows.Threading.DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
                                                System.Threading.SynchronizationContext.Current.Post(pl =>
                                                {
                                                    //里面写主要的逻辑
                                                    treeItem.Children.Add(childParentAdd);
                                                }, null);
                                            });

                                            int count = 1;
                                            //添加图像
                                            foreach (ImagesData image in imageDataList)
                                            {
                                                String[] slip1 = image.ftpPath.Split('/');
                                                String[] slip2 = image.ftpPath.Split('\\');
                                                string imageName = "";
                                                string path = "";
                                                FtpHelper ftp = new FtpHelper();

                                                if (slip1 != null && slip1.Length != 1)
                                                {
                                                    imageName = slip1[slip1.Length - 1];//获取最后一个

                                                    for (int k = 0; k < slip1.Length - 1; k++)
                                                    {
                                                        path += "\\" + slip1[k];
                                                    }
                                                    if (!File.Exists(filePath + "\\" + imageName))
                                                    {
                                                        donwLoadInfo = FtpHelper.Instance.donwLoadFile(ftpIp, ftpPort, ftpUserName, ftpPassword, upLoadModel, slip1, filePath);
                                                    }
                                                }
                                                else
                                                {
                                                    imageName = slip2[slip2.Length - 1];//获取最后一个
                                                    for (int k = 0; k < slip2.Length - 1; k++)
                                                    {
                                                        path += "\\" + slip2[k];
                                                    }
                                                    if (!File.Exists(filePath + "\\" + imageName))
                                                    {
                                                        donwLoadInfo = FtpHelper.Instance.donwLoadFile(ftpIp, ftpPort, ftpUserName, ftpPassword, upLoadModel, slip2, filePath);
                                                    }
                                                }
                                                image.imageName = imageName;
                                                if (donwLoadInfo != "")
                                                {
                                                    donwLoadFailCount++;
                                                    donwLoadInfoList.Add(donwLoadInfo);
                                                }

                                                TreeModel childAdd = new TreeModel();
                                                childAdd.count = count;
                                                childAdd.Type = bizType;
                                                if (image.isDelete.Equals(1))
                                                    childAdd.nameTag.Add("[删]");
                                                if (image.isAdd.Equals(1))
                                                    childAdd.nameTag.Add("[新增]");
                                                childAdd.Name = replenishInfoDataList[n].rep_Image_Code + "-" + childAdd.count + CommonUtil.getTreeModelNameTag(childAdd.nameTag);
                                                count++;
                                                childAdd.evaResult = replenishInfoDataList[n].eva_result;//补单方式
                                                childAdd.imageCode = replenishInfoDataList[n].main_Image_Code;
                                                childAdd.repImageCode = replenishInfoDataList[n].rep_Image_Code;
                                                childAdd.bizId = replenishInfoDataList[n].bizId;
                                                childAdd.imageName = image.imageName;
                                                childAdd.isBiSaoType = 1; //补单标识
                                                childAdd.ImageUrl = @"C:\MssClientCache\imageCache\" + replenishInfoDataList[n].rep_Image_Code + @"\" + image.imageName;//本地路径
                                                childAdd.ftpUrl = image.ftpPath;
                                                childAdd.httpUrl = image.httpPath;
                                                childAdd.isDelete = image.isDelete;//是否删除，1-删除，0或者空-不删除
                                                childAdd.Id = image.id;
                                                childAdd.imageScanTime = image.createTime;
                                                childAdd.imageOrder = image.imgOrder;
                                                childAdd.level = 3;
                                                childAdd.Date = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                                                childAdd.IsExpanded = true;
                                                childAdd.IsChecked = true;
                                                childAdd.Parent = childParentAdd;
                                                //“不支持从调度程序线程以外的线程对其 SourceCollection 进行的更改”的解决方法
                                                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                                                {
                                                    System.Threading.SynchronizationContext.SetSynchronizationContext(new
                                                        System.Windows.Threading.DispatcherSynchronizationContext(System.Windows.Application.Current.Dispatcher));
                                                    System.Threading.SynchronizationContext.Current.Post(pl =>
                                                    {
                                                        //里面写主要的逻辑
                                                        childParentAdd.Children.Add(childAdd);
                                                    }, null);
                                                });

                                            }
                                        }
                                    }
                                    #endregion
                                }
                                if (donwLoadInfoList.Count != 0)
                                    CommonUtil.ShowMsgFrom("下载失败共：" + donwLoadFailCount + "张图像，失败原因：" + donwLoadInfoList[0]);
                            };
                            worker.RunWorkerCompleted += (o, a) =>
                            {
                                CommonUtil.ShowMsgFrom("已新增" + (replenishInfoDataList.Count - failCount) + "个补单。");
                            };
                            worker.RunWorkerAsync();
                        }
                        else
                        {
                            CommonUtil.ShowMsgFrom("你已取消下载，本次加载补单数量为：0");
                        }
                    }
                    else
                    {
                        CommonUtil.ShowMsgFrom("没有新的补单任务，或者稍等一下再次点击获取。");
                    }
                }
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
            }
            return;
            #endregion
        }

        /// <summary>
        /// 在单据类型上添加分组
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addFolder_Click(object sender, RoutedEventArgs e)
        {
            addFolderByZsmTreeView();
        }


        /// <summary>
        /// ZsmTreeView控件调用生成文件夹
        /// </summary>
        public void addFolderByZsmTreeView()
        {
            #region
            if (null == ZsmTreeView.s_selectedTreeModel)
            {
                CMessageBox.Show("请先选择一个单据类型", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }
            if (1 != ZsmTreeView.s_selectedTreeModel.level)
            {
                CMessageBox.Show("现在选择的不是单据类型！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }
            TreeModel parentTree = ZsmTreeView.s_selectedTreeModel;

            TreeModel newChild = new TreeModel();
            newChild.bizId = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            newChild.Id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            newChild.Name = "新添加分组_" + DateTime.Now.ToString("sfff");
            newChild.IsExpanded = true;
            newChild.Parent = parentTree;
            newChild.IsSelected = true;
            newChild.IsChecked = false;
            newChild.level = 2;
            parentTree.Children.Add(newChild);
            #endregion
        }

        /// <summary>
        /// ftp模式切换按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void modelSet_Click(object sender, RoutedEventArgs e)
        {
            #region
            if (ftpModel.Header.Equals("被动模式"))
            {
                upLoadModel = 2;
                ftpModel.Header = "主动模式";
                CommonUtil.ShowMsgFrom("当前上传模式已切换为主动模式");
            }
            else
            {
                upLoadModel = 1;
                ftpModel.Header = "被动模式";
                CommonUtil.ShowMsgFrom("当前上传模式已切换为被动模式");
            }
            #endregion
        }

        /// <summary>
        /// 获取扫描单据-用于加载到目录树下
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MessageUnSelectedGet_Click(object sender, RoutedEventArgs e)
        {
            #region
            try
            {
                Dictionary<string, string> paramsDic = new Dictionary<string, string>();
                paramsDic.Add("password", "password");
                userNameCN.Dispatcher.Invoke(new Action(() =>
                {
                    paramsDic.Add("account", userNameCN.Content.ToString());
                }));
                paramsDic.Add("functionType", "getMessageUnSelected");
                paramsDic.Add("image_code", "00");
                paramsDic.Add("bizType", "00");
                paramsDic.Add("imageId", "00");
                paramsDic.Add("bizId", "00");
                string strResult = CommonUtil.buDanPost(Global.getInstance().strUrl + Global.getInstance().strBuDanInfo, paramsDic);
                if (null == strResult || "" == strResult || "[]".Equals(strResult))
                {
                    CommonUtil.ShowMsgFrom("没有获取到单据信息，请稍后再试");
                    return;
                }
                List<MessageUnSelectedData> MessageUnSelectedDataList = new List<MessageUnSelectedData>();
                MessageUnSelectedData MessageUnSelected = new MessageUnSelectedData();
                var ms = new MemoryStream(Encoding.UTF8.GetBytes(strResult));
                {
                    DataContractJsonSerializer deseralizer = new DataContractJsonSerializer(typeof(List<MessageUnSelectedData>));
                    MessageUnSelectedDataList = (List<MessageUnSelectedData>)deseralizer.ReadObject(ms);// //反序列化ReadObjects
                }
                if (MessageUnSelectedDataList.Count != 0)
                {
                    List<MessageUnSelectedData> newMessageUnSelectedDataList = new List<MessageUnSelectedData>();

                    List<int> posList = new List<int>();//记录当前存在的补单数据位置
                                                        //筛选新的补单任务：如果存在就记录数组的位置，目的是获取当前存在补单数据
                    for (int r = 0; r < MessageUnSelectedDataList.Count; r++)
                    {
                        foreach (TreeModel treeItem in m_treeList)
                        {
                            foreach (TreeModel child in treeItem.Children)
                            {
                                if (null != child.imageCode || "" == child.imageCode)
                                {
                                    if (child.imageCode.Equals(MessageUnSelectedDataList[r].imageCode))
                                    {
                                        posList.Add(r);
                                    }
                                }
                            }
                        }
                    }

                    //获取当前存在的补单
                    if (posList.Count != 0)
                    {
                        for (int p = 0; p < posList.Count; p++)
                        {
                            newMessageUnSelectedDataList.Add(MessageUnSelectedDataList[posList[p]]);
                        }
                    }

                    //从新获取的补单数据删除已存在的补单数据
                    for (int t = 0; t < newMessageUnSelectedDataList.Count; t++)
                    {
                        MessageUnSelectedDataList.Remove(newMessageUnSelectedDataList[t]);
                    }

                    //如果MessageUnSelectedDataList的数据为0，则提示
                    if (MessageUnSelectedDataList.Count == 0)
                    {
                        CommonUtil.ShowMsgFrom("暂无新的单据，请稍后再试");
                        return;
                    }

                    for (int i = 0; i < MessageUnSelectedDataList.Count; i++)
                    {
                        foreach (TreeModel treeItem in m_treeList)
                        {
                            if (treeItem.Id.Equals(MessageUnSelectedDataList[i].imageBizCode))
                            {
                                TreeModel child = new TreeModel();
                                child.bizId = MessageUnSelectedDataList[i].messageId;
                                child.imageCode = MessageUnSelectedDataList[i].imageCode;
                                child.Type = MessageUnSelectedDataList[i].imageBizCode;
                                child.level = 2;
                                child.Id = MessageUnSelectedDataList[i].id;
                                child.Name = MessageUnSelectedDataList[i].imageCode;
                                child.IsExpanded = true;
                                child.IsChecked = true;//默认不勾选
                                child.Parent = treeItem;
                                treeItem.Children.Add(child);
                            }
                        }
                    }
                    CommonUtil.ShowMsgFrom("已添加" + MessageUnSelectedDataList.Count + "个单据");
                }
                else
                {
                    CommonUtil.ShowMsgFrom("没有获取到单据信息，请稍后再试");
                    return;
                }
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
            }
            #endregion
        }

        private bool OpenOrClose = true;
        /// <summary>
        /// 全选按钮点击逻辑：OpenOrClose记录是全选还是取消操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void quanxuan_Click(object sender, RoutedEventArgs e)
        {
            #region
            if (OpenOrClose)
            {
                OpenOrClose = false;
                foreach (TreeModel tree in m_treeList)
                {
                    tree.IsChecked = true;
                    tree.SetChildrenChecked(true);
                }
                tvc.ItemsSourceData = m_treeList;
            } 
            else
            {
                OpenOrClose = true;
                foreach (TreeModel tree in m_treeList)
                {
                    tree.IsChecked = false;
                    tree.SetChildrenChecked(false);
                }
                tvc.ItemsSourceData = m_treeList;          
            }
            #endregion
        }

        private void moveImage(TreeModel selectNode, Stuff selectGroup)
        {
            #region
            //删除选择的
            TreeModel parentTree = ZsmTreeView.s_selectedTreeModel.Parent;
            //删除选择的图片
            parentTree.Children.Remove(ZsmTreeView.s_selectedTreeModel);
            //把剩下的图片名称重新排列
            int i = 1;
            foreach (TreeModel childChildren in parentTree.Children)
            {
                childChildren.count = i;
                childChildren.Name = parentTree.Name + "_" + childChildren.count + CommonUtil.getTreeModelNameTag(childChildren.nameTag);
                i++;
            }
            //转移
            foreach (TreeModel tree in m_treeList)
            {
                foreach (TreeModel treeChild in tree.Children)
                {
                    if (treeChild.Id.Equals(selectGroup.Id))
                    {
                        TreeModel newChild = new TreeModel();
                        newChild = selectNode;
                        newChild.count = treeChild.Children.Count + 1;
                        newChild.Name = treeChild.Name + "-" + newChild.count + CommonUtil.getTreeModelNameTag(newChild.nameTag);
                        newChild.Id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        newChild.bizId = DateTime.Now.ToString("yyyyMMddHHmmssff");
                        newChild.Date = DateTime.Now.ToString("yyyyMMddHHmmssff");
                        newChild.IsExpanded = true;
                        newChild.IsChecked = false;
                        //if (treeChild.isBiSaoType.Equals(1))
                        //{
                        //    newChild.repImageCode = treeChild.repImageCode;
                        //    newChild.isDelete = 2;
                        //    newChild.isBuSaoTag = 1;
                        //    newChild.isBiSaoType = 1;
                        //    newChild.bizId = treeChild.bizId;
                        //    newChild.Name = treeChild.repImageCode + "_" + (treeChild.Children.Count + 1) + "[补]";
                        //}
                        newChild.Barcode = "";
                        newChild.Parent = treeChild;
                        treeChild.Children.Add(newChild);
                    }
                }
            }

            ZsmTreeView.s_selectedTreeModel = null;
            #endregion
        }

        private void breakUpImageDelegate(String groupName)
        {
            #region
            IList<TreeModel> moveList = new List<TreeModel>();//收集勾选的节点
            ZsmTreeView.s_selectedTreeModel.IsChecked = true;
            TreeModel pranteNodeOfSelsct = ZsmTreeView.s_selectedTreeModel.Parent;//获取选择图像的上一父节点
            TreeModel ppranteNode = pranteNodeOfSelsct.Parent;//获取根节点
            String newGroupId = "";
            //获取勾选的图像，新建分组
            //新建分组
            TreeModel newChild = new TreeModel();
            newChild.Id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            newGroupId = newChild.Id;
            newChild.bizId = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            newChild.Name = groupName;
            newChild.imageCode = groupName;
            newChild.IsExpanded = true;
            newChild.IsChecked = false;
            newChild.level = 2;
            newChild.Parent = ppranteNode;
            ppranteNode.Children.Add(newChild);
            
            //获取勾选的图像
            foreach (TreeModel treeg in pranteNodeOfSelsct.Children)
            {
                if (treeg.IsChecked)
                {
                    moveList.Add(treeg);
                }
            }

            //删除三级目录
            for (int t = 0; t < moveList.Count; t++)
            {
                pranteNodeOfSelsct.Children.Remove(moveList[t]);
            }

            //重新排序
            int i = 1;//序号
            foreach (TreeModel child in pranteNodeOfSelsct.Children)
            {
                child.count = i;
                if (pranteNodeOfSelsct.isFail != 1 && child.isBiSaoType.Equals(0))
                {
                    child.Name = pranteNodeOfSelsct.Name + "-" + child.count + CommonUtil.getTreeModelNameTag(child.nameTag);
                }
                if (pranteNodeOfSelsct.isFail == 1 && child.isBiSaoType.Equals(1))
                    child.Name = pranteNodeOfSelsct.repImageCode + "-" + child.count + CommonUtil.getTreeModelNameTag(child.nameTag);
                i++;
            }

            //把勾选的图像转移到新建的分组
            foreach (TreeModel tree in m_treeList)
            {
                foreach (TreeModel treeChild in tree.Children)
                {
                    if (treeChild.Id.Equals(newGroupId))
                    {
                        int count = 1;
                        foreach (TreeModel treeg in moveList)
                        {
                            treeg.Parent = treeChild;
                            treeg.Name = treeChild.Name + "-" + count + CommonUtil.getTreeModelNameTag(treeg.nameTag);
                            treeChild.Children.Add(treeg);
                            count++;
                        }
                        break;
                    }
                }
            }
            ZsmTreeView.s_selectedTreeModel = null;
            #endregion
        }

        /// <summary>
        /// 图像不存时，删除对应的节点
        /// </summary>
        /// <param name="delItem"></param>
        private void deleteImage(TreeModel delItem)
        {
            #region
            TreeModel parentTree = delItem.Parent;
            parentTree.Children.Remove(delItem);
            int xuhao = 1;
            foreach (TreeModel t in parentTree.Children)
            {
                t.count = xuhao;
                if (t.isBiSaoType.Equals(1))//补单
                    t.Name = parentTree.repImageCode + "-" + t.count + CommonUtil.getTreeModelNameTag(t.nameTag);
                else if (t.isFail.Equals(1) && t.isBiSaoType.Equals(1))//上传失败 是补单
                    t.Name = parentTree.repImageCode + "-" + t.count + CommonUtil.getTreeModelNameTag(t.nameTag);
                else if(t.isFail.Equals(1))//上传失败
                    t.Name = parentTree.imageCode + "-" + t.count + CommonUtil.getTreeModelNameTag(t.nameTag);
                else
                    t.Name = parentTree.Name + "-" + t.count + CommonUtil.getTreeModelNameTag(t.nameTag);

                xuhao++;
            }
            ZsmTreeView.s_selectedTreeModel = null;
            #endregion
        }

        /// <summary>
        /// 预览图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void yulang_Click(object sender, RoutedEventArgs e)
        {
            #region
            try
            {
                if (null == ZsmTreeView.s_selectedTreeModel)
                {
                    CMessageBox.Show("请先选择一个分组或者分组下的图像！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                    return;
                }
                if (null == ZsmTreeView.s_selectedTreeModel.Parent)
                {
                    CMessageBox.Show("现在选择的不是一个分组或者分组下的图像！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                    return;
                }

                grd.Visibility = Visibility.Collapsed;
                info.Visibility = Visibility.Collapsed;
                IList<TreeModel> trees = new List<TreeModel>();

                if (ZsmTreeView.s_selectedTreeModel.Children.Count == 0 && ZsmTreeView.s_selectedTreeModel.Parent.Parent == null)
                {
                    CMessageBox.Show("该分组下没有图像！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                    return;
                }
              
                if (0 != ZsmTreeView.s_selectedTreeModel.Children.Count)
                {
                    trees = ZsmTreeView.s_selectedTreeModel.Children;
                }
                if (ZsmTreeView.s_selectedTreeModel.Children.Count == 0)
                {
                    trees = ZsmTreeView.s_selectedTreeModel.Parent.Children;
                }

                //ListBox添加item
                List<ImagePereview> photos = new List<ImagePereview>();
                for (int i = 0; i < trees.Count; i++)
                {
                    photos.Add(new ImagePereview()
                    {
                        imagePath = trees[i].ImageUrl,
                        Name = "测试" + i,
                        treeId = trees[i].Id
                    });
                }
                listBox.Visibility = Visibility.Visible;
                listBox.ItemsSource = photos;
                listBox.DataContext = photos;
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
            }
            #endregion
        }

        private void images_Click(object sender, MouseButtonEventArgs e)
        {
            #region
            grd.Visibility = Visibility.Visible;
            //yulanGri.Visibility = Visibility.Hidden;

            System.Windows.Controls.Image img = (System.Windows.Controls.Image)sender;
            BitmapImage bim= CommonUtil.Bitmap2BitmapImageFromImagrPath(img.Uid);
            MainImage.Source = bim;
            GC.Collect(); //强制回收资源  
            GC.WaitForPendingFinalizers();
            #endregion
        }

        private List<List<TreeModel>> backList = new List<List<TreeModel>>();//收集勾选的节点
        private void merge_Click(object sender, RoutedEventArgs e)
        {
            #region
            try
            {
                List<TreeModel> mergeList = new List<TreeModel>();//收集勾选的节点
                List<TreeModel> mergeListTemp = new List<TreeModel>();//收集勾选的节点
                String imagePath = "";
                if (3 != ZsmTreeView.s_selectedTreeModel.level)
                {
                    CMessageBox.Show("现在选择的不是具体的图像！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                    return;
                }
                if (null == ZsmTreeView.s_selectedTreeModel)
                {
                    CMessageBox.Show("请先用鼠标左键选中需要合并的两张图像！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                    return;
                }
                if (ZsmTreeView.s_selectedTreeModel.isBiSaoType.Equals(1) || ZsmTreeView.s_selectedTreeModel.isBuSaoTag.Equals(1))
                {
                    CMessageBox.Show("补单单据不能合并！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                    return;
                }

                //ZsmTreeView.s_selectedTreeModel.IsChecked = true;

                TreeModel pranteNodeOfSelsct = ZsmTreeView.s_selectedTreeModel.Parent;//获取选择图像的上一父节点

                //获取勾选的图像
                foreach (TreeModel treeg in pranteNodeOfSelsct.Children)
                {
                    if (treeg.IsChecked)
                    {
                        if (treeg.isBiSaoType.Equals(1))
                        {
                            CMessageBox.Show("补单类型的图像不能合并！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                            return;
                        }
                        if (treeg.IsIdentifying.Equals(1))
                        {
                            CMessageBox.Show("所选的数据含有发票，发票不能合并！！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                            return;
                        }
                        if (treeg.isMerge.Equals(1))
                        {
                            CMessageBox.Show("不能选择已经合并过的图像！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                            return;
                        }
                        //记录信息
                        TreeModel treeTemp = new TreeModel();
                        treeTemp.ImageUrl = treeg.ImageUrl;
                        treeTemp.Id = treeg.Id;
                        treeTemp.Date = treeg.Date;
                        treeTemp.isBuSaoTag = treeg.isBuSaoTag;
                        treeTemp.Parent = treeg.Parent;
                        mergeList.Add(treeg);//合并操作需要的数据
                        mergeListTemp.Add(treeTemp);//撤销合并需要的数据
                    }
                }

                if (mergeList.Count > 2)
                {
                    CMessageBox.Show("只能合并同一分组下的两张！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                    return;
                }
                if (mergeList.Count < 2)
                {
                    CMessageBox.Show("需要选择同一分组下的两张！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                    return;
                }

                backList.Add(mergeListTemp);//把合并的信息记录把数据里，用于还原时的操作

                ImageEdit imageEditDlg = new ImageEdit(mergeList[0].ImageUrl, mergeList[1].ImageUrl);
                imageEditDlg.Owner = this;
                imageEditDlg.Show();
                imageEditDlg.mergeImage += (String path, String Url1, String Url2) =>
                {
                    imagePath = path;
                    if (imagePath != "")
                    {
                        pranteNodeOfSelsct.Children.Remove(mergeList[1]);
                        //把剩下的图片名称重新排列
                        int i = 1;
                        foreach (TreeModel childChildren in pranteNodeOfSelsct.Children)
                        {
                            childChildren.count = i;
                            if (childChildren.Id.Equals(mergeList[0].Id))
                            {
                                childChildren.nameTag.Add("[合]");
                                childChildren.Name = pranteNodeOfSelsct.Name + "-" + childChildren.count + CommonUtil.getTreeModelNameTag(childChildren.nameTag);
                                childChildren.ImageUrl = imagePath;
                                childChildren.isMerge = 1;//标识合并
                                i++;
                                continue;
                            }
                            if (pranteNodeOfSelsct.isFail.Equals(1))
                            {
                                childChildren.Name = pranteNodeOfSelsct.imageCode + "-" + childChildren.count + CommonUtil.getTreeModelNameTag(childChildren.nameTag);
                                i++;
                                continue;
                            }
                            childChildren.Name = pranteNodeOfSelsct.Name + "-" + childChildren.count + CommonUtil.getTreeModelNameTag(childChildren.nameTag);
                            i++;
                        }
                    }
                    MainImage.Source = CommonUtil.Bitmap2BitmapImageFromImagrPath(imagePath);
                };
                ZsmTreeView.s_selectedTreeModel = null;
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
                return;
            }
            #endregion
        }

        /// <summary>
        /// 针对合并图片的撤销操作，只能撤销本次登录下的所有合并操作
        /// 选择合并的节点，匹配记录的原节点，看是否匹配，匹配就回退，匹配完成后删除这次撤销的数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void back_Click(object sender, RoutedEventArgs e)
        {
            #region
            List<TreeModel> mergeListTemp = new List<TreeModel>();
            if (backList.Count.Equals(0))
            {
                CMessageBox.Show("还没有进行过合并操作！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }
            if (null == ZsmTreeView.s_selectedTreeModel)
            {
                CMessageBox.Show("请先用鼠标左键选中标识 [合] 图像！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }
            if (ZsmTreeView.s_selectedTreeModel.isMerge.Equals(0))
            {
                CMessageBox.Show("目前选择的图像没有被合并过，不能撤销合并！", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
                return;
            }
            TreeModel pranteNodeOfSelsct = ZsmTreeView.s_selectedTreeModel.Parent;//获取选择图像的上一父节点

            for (int i=0;i<backList.Count;i++)
            {
                List<TreeModel> mergeList = backList[i];
                mergeListTemp = mergeList;
                if (mergeList[0].Parent.Id.Equals(pranteNodeOfSelsct.Id))
                {
                    int index = pranteNodeOfSelsct.Children.IndexOf(ZsmTreeView.s_selectedTreeModel);//定位合并的节点在数组中位置
                    pranteNodeOfSelsct.Children[index].ImageUrl = mergeList[0].ImageUrl;//替换图像的路径
                    if (pranteNodeOfSelsct.isBiSaoType.Equals(1))
                    {
                        pranteNodeOfSelsct.Children[index].isBuSaoTag = 1;
                    }
                    pranteNodeOfSelsct.Children[index].isMerge = 0;//还原合并状态为0
                    pranteNodeOfSelsct.Children[index].IsChecked = false;
                    pranteNodeOfSelsct.Children[index].Parent = pranteNodeOfSelsct;
                    pranteNodeOfSelsct.Children[index].nameTag.Clear();

                    //还原第二个节点
                    TreeModel treeTemp = new TreeModel();
                    if (pranteNodeOfSelsct.isBiSaoType.Equals(1))
                    {
                        treeTemp.isBuSaoTag = 1;
                    }
                    treeTemp.ImageUrl = mergeList[1].ImageUrl;
                    treeTemp.Id = mergeList[1].Id;
                    treeTemp.Date = mergeList[1].Date;
                    treeTemp.isMerge = 0;
                    treeTemp.IsChecked = false;
                    treeTemp.level = 3;
                    treeTemp.Parent = pranteNodeOfSelsct;

                    pranteNodeOfSelsct.Children.Insert(index+1, treeTemp);//在定位的节点前面插入原来的未合并的节点
                    //重新排序
                    int count = 1;
                    foreach (TreeModel childChildren in pranteNodeOfSelsct.Children)
                    {
                        childChildren.count = count;
                        childChildren.Name = pranteNodeOfSelsct.Name + "-" + count + CommonUtil.getTreeModelNameTag(childChildren.nameTag);
                        count++;
                        if (childChildren.isFail.Equals(1) && childChildren.isBiSaoType.Equals(1))
                            childChildren.Name = pranteNodeOfSelsct.repImageCode + "_" + childChildren.count + CommonUtil.getTreeModelNameTag(childChildren.nameTag);
                        else
                            childChildren.Name = pranteNodeOfSelsct.imageCode + "_" + childChildren.count + CommonUtil.getTreeModelNameTag(childChildren.nameTag);
                    }
                }
            }
            ZsmTreeView.s_selectedTreeModel = null;
            backList.Remove(mergeListTemp);//撤销完后，移除本次撤销的数据
            MainImage.Source = CommonUtil.Bitmap2BitmapImageFromImagrPath(mergeListTemp[0].ImageUrl);//指向合并前的第一张图像
            #endregion
        }

        /// <summary>
        /// 标识勾选的图片为发票，ocr将进行优先识别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void identifying_Click(object sender, RoutedEventArgs e)
        {
            #region
            CMessageBoxResult cmr = CMessageBox.Show("是否将 [勾选] 的图片标识为发票,标识为发票将优先识别(注意：补单单据不会标识)", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
            if (cmr == CMessageBoxResult.OK)
            {
                //清除所有标识
                //foreach (TreeModel child1 in m_treeList)
                //{
                //    foreach (TreeModel child2 in child1.Children)
                //    {
                //        foreach (TreeModel child3 in child2.Children)
                //        {
                //            child3.IsIdentifying = 0;
                //            child3.Name=child3.Name.Replace("_发票", "");
                //        }
                //    }
                //}
                //添加勾选标识
                foreach (TreeModel child1 in m_treeList)
                {
                    foreach (TreeModel child2 in child1.Children)
                    {
                        foreach (TreeModel child3 in child2.Children)
                        {
                            if (child3.IsChecked)
                            {
                                //补单单据不做标识
                                if (child3.isBiSaoType.Equals(1))
                                    continue;
                                if (child3.IsIdentifying != 1)
                                {
                                    child3.nameTag.Add("[发票]");
                                    child3.Name = child3.Parent.imageCode +"-"+ child3.count + CommonUtil.getTreeModelNameTag(child3.nameTag);
                                    child3.IsOCRSuccess = 0;
                                    child3.IsIdentifying = 1;
                                }
                            }
                        }
                    }
                }
            }
            #endregion
        }
        private void grdMap_MouseDown(object sender, MouseButtonEventArgs e)
        {
            isDrag = true;
            startPoint = e.GetPosition(grd);
        }

        private void grdMap_MouseUp(object sender, MouseButtonEventArgs e)
        {
            isDrag = false;
        }

        private void grdMap_MouseLeave(object sender, MouseEventArgs e)
        {
            isDrag = false;
        }

        private void grdMap_MouseMove(object sender, MouseEventArgs e)
        {
            #region
            if (isDrag)
            {
                System.Windows.Point p = e.GetPosition(grd);
                System.Windows.Point topPoint = grd.TranslatePoint(new System.Windows.Point(0, 0), grd);
                System.Windows.Point bottomPoint = grd.TranslatePoint(new System.Windows.Point(grd.ActualWidth, grd.ActualHeight), grd);

                double moveX = p.X - startPoint.X;
                double moveY = p.Y - startPoint.Y;
                tt.X += (p.X - startPoint.X);
                startPoint.X = p.X;
                tt.Y += (p.Y - startPoint.Y);
                startPoint.Y = p.Y;
                //向上向下移动条件判断（会有一点点的小偏移，如果想更精确的控制，那么分向上和向下两种情况，并判断边距）
                //if ((moveY < 0 && bottomPoint.Y > grd.ActualHeight) || (moveY > 0 && topPoint.Y < 0))
                //{
                //    tt.Y += (p.Y - startPoint.Y);
                //    startPoint.Y = p.Y;
                //}

                ////向左向右移动条件判断
                //if ((moveX < 0 && bottomPoint.X > grd.ActualWidth) || (moveX > 0 && topPoint.X < 0))
                //{
                //    tt.X += (p.X - startPoint.X);
                //    startPoint.X = p.X;
                //}
            }
            #endregion
        }
        private void showGrid()
        {
            TreeModel selectTree = ZsmTreeView.s_selectedTreeModel;
            #region
            if (selectTree.level.Equals(3))
            {
                grd.Visibility = Visibility.Visible;
                listBox.Visibility = Visibility.Collapsed;
                listBox.DataContext = null;
                listBox.ItemsSource = null;
                listBox.Items.Clear();
                if (selectTree.IsIdentifying.Equals(1))
                {
                    InvoiceModel invoiceModel = new InvoiceModel();
                    invoiceModel = ZsmTreeView.s_selectedTreeModel.InvoiceModelFun;
                    if ("" != invoiceModel.invoiceCode && "" != invoiceModel.invoiceType && "" != invoiceModel.invoiceNum)
                    {
                        invoiceBtn.Visibility = Visibility.Visible;
                        info.Visibility = Visibility.Visible;
                        List<InvoiceListViewModel> list = new List<InvoiceListViewModel>();
                        list.Add(new InvoiceListViewModel("invoiceType", invoiceModel.invoiceType));
                        list.Add(new InvoiceListViewModel("invoiceCode", invoiceModel.invoiceCode));
                        list.Add(new InvoiceListViewModel("invoiceNum", invoiceModel.invoiceNum));
                        list.Add(new InvoiceListViewModel("invoiceDate", invoiceModel.invoiceDate));
                        list.Add(new InvoiceListViewModel("checkCode", invoiceModel.checkCode));
                        list.Add(new InvoiceListViewModel("amount", invoiceModel.amount));

                        invoiceList.DataContext = list;
                        invoiceList.ItemsSource = list;
                    }
                }
                else
                {
                    invoiceBtn.Visibility = Visibility.Collapsed;
                    info.Visibility = Visibility.Collapsed;
                }
            }
            else
            {
                invoiceBtn.Visibility = Visibility.Collapsed;
                info.Visibility = Visibility.Collapsed;
            }
            #endregion
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (invoiceBtn.Content.ToString() == "隐藏发票信息")
            {
                invoiceBtn.Content = "显示发票信息";
                info.Height = 30;
                invoiceList.Visibility = Visibility.Collapsed;
            }
            else
            {
                invoiceBtn.Content = "隐藏发票信息";
                info.Height = 170;
                invoiceList.Visibility = Visibility.Visible;
            }
        }

        private void popupContent_Closed(object sender, EventArgs e)
        {
            this.listModle.PopupIsOpen = false;
        }

        private void item_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            this.listModle.PopupIsOpen = false;
        }

        private void queding_Button_Click(object sender, RoutedEventArgs e)
        {
            this.listModle.PopupIsOpen = false;
        }

        private void succeseListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            CommonUtil.ClipboardFunction(succeseListView);
        }

        private void upLoadList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            CommonUtil.ClipboardFunction(upLoadList);
        }

        private void FailListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            CommonUtil.ClipboardFunction(FailListView);
        }

        private void invoiceList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

        }

        private void upLoadType_Click(object sender, RoutedEventArgs e)
        {
            #region
            if (upLoadType.Header.Equals("应用上传"))
            {
                ftpModel.IsEnabled = true;
                upLoadTypeTag = 1;
                upLoadType.Header = "FTP上传";
                CommonUtil.ShowMsgFrom("当前上传形式已切换为 [FTP上传]");
            }
            else
            {
                upLoadTypeTag = 2;
                upLoadType.Header = "应用上传";
                ftpModel.IsEnabled = false;
                CommonUtil.ShowMsgFrom("当前上传形式已切换为 [应用上传]");
            }
            #endregion
        }

        private void updateInfo_Click(object sender, RoutedEventArgs e)
        {
            #region
            //获取数据库系统版本信息
            Dictionary<string, string> paramsDic = new Dictionary<string, string>();
            paramsDic.Add("account", "username");
            paramsDic.Add("password", "password");
            paramsDic.Add("key", "key");
            paramsDic.Add("func", "keyInfo");
            var versionModel = CommonUtil.getSysProperty("New_Version");
            
            if (versionModel.value != null && versionModel.updateDate !=null && versionModel.description!=null)
                CMessageBox.UpgradeShow("有新版本，是否下载更新。\n\n" + "版本号：" +
                    versionModel.value + "\n" + "更新时间：" + versionModel.updateDate + "\n" + 
                    "更新内容：" + versionModel.description, "更新提示", 
                    CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
            else
                MessageBox.Show("获取更新信息出错");
            #endregion
        }

        public void UpgradeFileCreate(object source, FileSystemEventArgs e)
        {
            if (File.Exists("C://MssClientCache//BudanInfoGet.txt"))
            {
                //判断是否存在已经打开的客户端，有的话就定位显示在最前面
                Process tProcess = CommonUtil.RunningInstance2();
                if (null != tProcess)
                {
                    File.Delete("C://MssClientCache//BudanInfoGet.txt");//删除标识文件
                    ShowWindowAsync(tProcess.MainWindowHandle, WS_SHOWNORMAL); //显示客户端
                    SetForegroundWindow(tProcess.MainWindowHandle);            //显示客户端在最前面
                }
                Thread.Sleep(1000);
                BudanInfoGet(false);
            }
        }

        private void ListBoxItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                ListBoxItem listBoxItem = (ListBoxItem)sender;
                ImagePereview imagePereview = (ImagePereview)listBoxItem.DataContext;
                MainImage.Source = new BitmapImage(new Uri(imagePereview.imagePath));
                showGrid();
                GC.Collect(); //强制回收资源  
                GC.WaitForPendingFinalizers();
            }
            catch (Exception ex)
            {
                CommonUtil.WriteLog(ex);
            }
        }

        private void ListBoxItem_MouseDown(object sender, MouseButtonEventArgs e)
        {
            ListBoxItem listBoxItem = (ListBoxItem)sender;
            ImagePereview imagePereview = (ImagePereview)listBoxItem.DataContext;
            IList<TreeModel> treeList = tvc.Level3Items();
            foreach (TreeModel t in treeList)
            {
                if (t.Id.Equals(imagePereview.treeId))
                {
                    ZsmTreeView.s_selectedTreeModel = t;
                    ZsmTreeView.s_selectedTreeModel.IsSelected = true;
                }
            }
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            //if (e.Key.Equals(Key.Up))
            //{
            //    MessageBox.Show("捕获键盘上键");
            //}
            //if (e.Key.Equals(Key.Down))
            //{
            //    MessageBox.Show("捕获键盘下键");
            //}
        }

        private void CancelInvoiceTag(object sender, RoutedEventArgs e)
        {
            #region
            CMessageBoxResult cmr = CMessageBox.Show("是否取消所 [勾选] 图像的发票标识", "提示信息", CMessageBoxButton.OKCancel, CMessageBoxImage.None, CMessageBoxDefaultButton.OK);
            if (cmr == CMessageBoxResult.OK)
            {
                //添加勾选标识
                foreach (TreeModel child1 in m_treeList)
                {
                    foreach (TreeModel child2 in child1.Children)
                    {
                        foreach (TreeModel child3 in child2.Children)
                        {
                            if (child3.IsChecked)
                            {
                                //补单单据不做标识
                                if (child3.isBiSaoType.Equals(1))
                                    continue;
                                if (child3.IsIdentifying == 1)
                                {
                                    child3.nameTag.Remove("[发票]");
                                    child3.Name = child3.Parent.imageCode +"-"+ child3.count + CommonUtil.getTreeModelNameTag(child3.nameTag);
                                    child3.IsOCRSuccess = 0;
                                    child3.IsIdentifying = 0;
                                }
                            }
                        }
                    }
                }
            }
            #endregion
        }




        //------------------底部分割线---------------------------
    }
}
